how to convert ISO_LOCAL_DATE to date time format : yyyy-MM-dd'T'HH:mm:ss.SSSZ in java
Ex: given date: 2016-01-25 to 2016-01-25T00:00:00.000+0100
I am assuming that you have got a string, for example 2016-01-25
, and that you want a string containing the start of the day in the JVM’s default time zone (it wasn’t clear from the question). I first define a formatter for the format that you want (it’s ISO 8601):
private static DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSxx");
Now your conversion goes:
String isoLocalDateString = "2016-01-25";
LocalDate date = LocalDate.parse(isoLocalDateString);
ZonedDateTime dateTime = date.atStartOfDay(ZoneId.systemDefault());
String dateTimeString = dateTime.format(formatter);
System.out.println(dateTimeString);
When running in my time zone, Europe/Copenhagen, output from this example code is what you asked for:
2016-01-25T00:00:00.000+0100
In rare cases where summer time (DST) begins at the first moment of the day, the time of day will not be 00:00:00.000.
For parsing with ISO_LOCAL_DATE
we don’t need to specify the formatter since this formatter is the default for LocalDate.parse()
.
All of this said, you should not normally want to convert a date from one string format to another string format. Inside your program keep dates as LocalDate
objects. When you get string input, parse into a LocalDate
. Only when you need to give string output, for example in data exchange with another system, format into a string in the required format.