Skip to main content

How do I convert date to and from a string

In this Q&A, we'll go over how to convert string to a date and time and vice versa using Java 8 APIs

Java Time classes provide parse methods to convert a string to a date(time) object

LocalDate ld = LocalDate.parse("2016-12-01");
LocalDateTime ldt = LocalDateTime.parse("2016-12-01T01:00:00");
ZonedDateTime zdt = ZonedDateTime.parse("2016-12-01T01:00:00-05:00");

An optional DateTimeFormatter class can also be provided to parse the String
DateTimeFormatter fb = DateTimeFormatter.ofPattern("dd-MMM-yyyy HH:mm:ss");
LocalDateTime ldt2 = LocalDateTime.parse("01-Dec-2019 01:00:00", fb );

DateTimeFormatter can also be used to print format date to a string
ZonedDateTime zdt = ZonedDateTime.parse("2016-12-01T01:00:00-05:00");
DateTimeFormatter fb = DateTimeFormatter.ofPattern("dd-MMM-yyyy HH:mm:ss");
System.out.println(zdt.format( fb ));

One can also the use Joda Time or the Apache commons library.  Author has not found a need to use or explore these classes

Comments