javastringjava-timezoneddatetime

How to format a ZonedDateTime to a String?


I want to convert a ZonedDateTime to a String in the format of ("dd/MM/yyyy - hh:mm"). I know this is possible in Joda-Time using their toString("dd/MM/yyyy - hh:mm"), but this doesn't work with ZonedDateTime.toString().

How can I format a ZonedDateTime to a String?


EDIT:

I tried to print the time in another timezone and the result appears to always be the same:

ZonedDateTime date = ZonedDateTime.now();
ZoneId la = ZoneId.of("America/Los_Angeles");
ZonedDateTime date2 = date.of(date.toLocalDateTime(), la);

// 24/02/2017 - 04:53
System.out.println(DateTimeFormatter.ofPattern("dd/MM/yyyy - hh:mm").format(date));
// same result as the previous one
// 24/02/2017 - 04:53
System.out.println(DateTimeFormatter.ofPattern("dd/MM/yyyy - hh:mm").format(date2));

And I am not in the same timezone as Los Angeles.


EDIT 2:

I found how to change the timezones:

// Change this:
ZonedDateTime date2 = date.of(date.toLocalDateTime(), la); // incorrect!
// To this:
ZonedDateTime date2 = date.withZoneSameInstant(la);

Solution

  • You can use java.time.format.DateTimeFormatter. https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html

    Here is an example

    ZonedDateTime date = ZonedDateTime.now();
            
    System.out.println(DateTimeFormatter.ofPattern("dd/MM/yyyy - hh:mm").format(date));