Format ZonedDateTime to String in Java

Learn to convert a ZonedDateTime instance to string using ZonedDateTime.format(DateTimeFormatter) method in Java.

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 !!

Sourcecode Download

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.