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

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode