Java: Adding TimeZone to DateTimeFormatter

后端 未结 2 1099
面向向阳花
面向向阳花 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:15

    The LocalDateTime class does not support time zones; you can use ZonedDateTime instead.

    ZonedDateTime now = ZonedDateTime.now();
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm:ss a z");
    System.out.println(now.format(formatter));
    

    This no longer throws an exception and prints 06:08:20 PM EDT for me, but the timezone will differ depending on your location.

提交回复
热议问题