Convert ZonedDateTime to LocalDateTime at time zone

前端 未结 4 1995
傲寒
傲寒 2020-12-28 15:42

I have an object of ZonedDateTime that is constructed like this

ZonedDateTime z = ZonedDateTime.of(LocalDate.now().atTime(11, 30), ZoneOffset.UT         


        
4条回答
  •  星月不相逢
    2020-12-28 15:45

    Another option that seems a little more intuitive is to convert the zoned date to an instant, then use LocalDateTime.ofInstant:

    ZonedDateTime z = ZonedDateTime.of(LocalDate.now().atTime(11, 30), ZoneOffset.UTC);
    ZoneId z = ZoneId.of("US/Central");
    LocalDateTime l = LocalDateTime.ofInstant(z.toInstant(), z);
    

    I prefer this to withZoneSameInstant because that solution little more opaque - you're getting a ZonedDateTime that has to be in a particular internal state (the correct time zone). Using ofInstant can be used on any ZonedDateTime in any time zone.

提交回复
热议问题