ZonedDateTime.withZoneSameInstant和ZonedDateTime.withZoneSameLocal有什么区别?

编程入门 行业动态 更新时间:2024-10-11 03:26:06
本文介绍了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有什么区别?

本文发布于:2023-10-29 00:54:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1538226.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有什么区别   ZonedDateTime   withZoneSameInstant   withZoneSameLocal

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!