What is the difference between ZonedDateTime.withZoneSameInstant and ZonedDateTime.withZoneSameLocal?

后端 未结 1 557
长发绾君心
长发绾君心 2021-02-15 04:10

Let\'s say I have a ZonedDateTime:

ZonedDateTime zonedDateTime = 
     ZonedDateTime.of(LocalDateTime.now(), ZoneId.of(\"US/Pacific\"));

I woul

1条回答
  •  名媛妹妹
    2021-02-15 04:21

    If you want to convert a timestamp from one timezone to another, use withZoneSameInstant(). withZoneSameLocal() will change the zone but keep all the other fields the same. The exception is where it would be an invalid date in that timezone.

    For example,

    ZonedDateTime dtUTC = ZonedDateTime.parse("2019-03-10T02:30:00Z");
    ZoneId pacific = ZoneId.of("US/Pacific");
    System.out.println(dtUTC.withZoneSameInstant(pacific));
    System.out.println(dtUTC.withZoneSameLocal(pacific));
    

    prints

    2019-03-09T18:30-08:00[US/Pacific]
    2019-03-10T03:30-07:00[US/Pacific]
    

    The first line is the original timestamp converted to another timezone. The second tries to preserve the date/time fields, but 2:30 is not a valid time on that date (because of the Daylight Savings jump), so it shifts it by an hour.

    0 讨论(0)
提交回复
热议问题