Learn to convert a ZonedDateTime
instance to string using ZonedDateTime.format(DateTimeFormatter)
method in Java.
Table Of Contents
1. Inbuilt Formatters
DateTimeFormatter
class has many inbuilt formatters which we can use in most of the cases e.g.
ISO_ZONED_DATE_TIME
– formats or parses a date-time with offset and zone, such as ‘2011-12-03T10:15:30+01:00[Europe/Paris]’.ISO_DATE_TIME
– formats or parses a date-time with the offset and zone if available, such as ‘2011-12-03T10:15:30’, ‘2011-12-03T10:15:30+01:00’ or ‘2011-12-03T10:15:30+01:00[Europe/Paris]’.ISO_INSTANT
– formats or parses an instant in UTC, such as ‘2011-12-03T10:15:30Z’.
A full list of formatters is listed in here.
ZonedDateTime zdt = ZonedDateTime.now();
String formattedZdt = zdt.format(DateTimeFormatter.ISO_ZONED_DATE_TIME);
System.out.println(formattedZdt);
formattedZdt = zdt.format(DateTimeFormatter.ISO_DATE_TIME);
System.out.println(formattedZdt);
formattedZdt = zdt.format(DateTimeFormatter.ISO_INSTANT);
System.out.println(formattedZdt);
Program output.
2022-02-17T22:22:54.4786538+05:30[Asia/Calcutta]
2022-02-17T22:22:54.4786538+05:30[Asia/Calcutta]
2022-02-17T16:52:54.478653800Z
2. Custom Formats
Using DateTimeFormatter.ofPattern()
, we can create our own custom formatters and use them just like above.
Java example to use custom formatter to format a zoned datetime instance to string.
DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("MM/dd/yyyy - HH:mm:ss z");
ZonedDateTime zdt = ZonedDateTime.now();
String formattedZdt = zdt.format(formatter);
System.out.println(formattedZdt);
Program output.
02/17/2022 - 22:25:03 IST
Happy Learning !!
Was this post helpful?
Let us know if you liked the post. That’s the only way we can improve.