ZonedDateTime.withZoneSameInstant和ZonedDateTime.withZoneSameLocal有什么区别? [英] What is the difference between ZonedDateTime.withZoneSameInstant and ZonedDateTime.withZoneSameLocal?

查看:561
本文介绍了ZonedDateTime.withZoneSameInstant和ZonedDateTime.withZoneSameLocal有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个ZonedDateTime:

Let's say I have a ZonedDateTime:

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

我想知道在柏林说的是哪个日期/时间. 我有两种方法:

I would like to know which date/time it is let's say in Berlin. I have two methods :

zonedDateTime.withZoneSameInstant(ZoneId.of("Europe/Berlin")); // probably this is the right one to get the corresponding date/time in Berlin

zonedDateTime.withZoneSameLocal(ZoneId.of("Europe/Berlin"));

withZoneSameLocal方法的文档说:仅在新区域无效的情况下才更改本地日期时间...",目前尚不清楚何时会真正发生(任何示例?=)

The docs for the withZoneSameLocal method say: "The local date-time is only changed if it is invalid for the new zone..." and it's not clear when this really can happen (any example ? =)).

它们各自代表哪个日期/时间,有什么区别?

推荐答案

如果要将时间戳从一个时区转换为另一个时区,请使用withZoneSameInstant(). withZoneSameLocal()将更改区域,但其他所有字段保持不变.唯一的例外是该时区中的无效日期.

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.

例如,

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));

打印文件

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

第一行是转换为另一个时区的原始时间戳.第二个尝试保留日期/时间字段,但是2:30不是该日期的有效时间(由于夏令时的跳跃),因此将其移动了一个小时.

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.

这篇关于ZonedDateTime.withZoneSameInstant和ZonedDateTime.withZoneSameLocal有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆