Java: Adding TimeZone to DateTimeFormatter

后端 未结 2 1103
面向向阳花
面向向阳花 2020-12-20 14:18

The LocalDateTime API gives the possibility to add the TimeZone Name by using the key \"z\" in the formatter. I get an exception adding this key and don\'t understand why. I

2条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-20 15:02

    LocalDateTime has two fields of type LocalDate and LocalTime.
    LocalDate has fields day, month, and year.
    LocalTime has fields hour, minute, second, and nano.

    Nowhere in that is a time zone given. Which is by nature, since the javadoc of LocalDateTime says:

    A date-time without a time-zone

    So, if the "local" date/time value is already representing a time in UTC, and you want it formatted saying so, you have multiple options:

    • Change the LocalDateTime to a ZonedDateTime by calling atZone():

      System.out.println(time.atZone(ZoneOffset.UTC)
                             .format(DateTimeFormatter.ofPattern("hh:mm:ss a z")));
      
    • Specify an override time zone in the formatter by calling withZone():

      System.out.println(time.format(DateTimeFormatter.ofPattern("hh:mm:ss a z")
                                                      .withZone(ZoneOffset.UTC)));
      
    • Format with a literal Z character:

      System.out.println(time.format(DateTimeFormatter.ofPattern("hh:mm:ss a 'Z'")));
      

    All three of the above outputs:

    11:59:22 PM Z


    Now, if the "local" date/time is really in a different time zone, you can use either of the first two, and just specify the actual zone.

    E.g. if time zone is -04:00, use ZoneOffset.ofHours(-4), and you'll get:

    11:59:22 PM -04:00

    Or if you are in New York, use ZoneId.of("America/New_York"), and you'll get:

    11:59:22 PM EDT

    If the "local" date/time is for New York, but you want formatted text to be UTC, use both at the same time, i.e.

    System.out.println(time.atZone(ZoneId.of("America/New_York"))
                           .format(DateTimeFormatter.ofPattern("hh:mm:ss a z")
                                                    .withZone(ZoneOffset.UTC)));
    

    With that, you get the time converted to:

    03:59:22 AM Z

提交回复
热议问题