使用 java.time
封装:
我正在将用户输入的自由插入的日期时间(年、月、日、小时、分钟)转换为 LocalDateTime
然后根据用户的时区,到 ZonedDateTime
.
爱沙尼亚示例:
LocalDateTime local = LocalDateTime.of(2018, 10, 28, 3, 30); // October 28th 03:30
ZonedDateTime zoned = local.atZone(ZoneId.of("Europe/Tallinn"));
上述时间 03:30 在时间线上可能意味着两个实例,因为爱沙尼亚的夏令时于 2018 年 10 月 28 日结束。在 04:00 GMT+3,时钟更改为 03:00 GMT+2,这意味着当天两次到达 03:30。根据the documentation of atZone()
,转换后的时间为夏季时间 03:30 GMT+3(强调我的时间):
In most cases, there is only one valid offset for a local date-time. In the case of an overlap, where clocks are set back, there are two valid offsets. This method uses the earlier offset typically corresponding to "summer".
我希望这种转换不要隐式进行。相反,我想捕获异常并通知用户有关不明确的输入。似乎有一个方法可以做到这一点,但我不明白的是为什么该方法是静态的并接受三个参数。如何针对我的情况正确使用它?来自同一文档:
To throw an exception when there is a gap or overlap, use
ZonedDateTime.ofStrict(LocalDateTime, ZoneOffset, ZoneId)
.
为什么它要求 ZoneOffset
争论?在我看来,我所需要的只是一个 LocalDateTime
和ZoneId
。否则,每次我转换为 ZonedDateTime
,我如何知道是使用GMT+2还是GMT+3的偏移量?这是我希望 Java 告诉我的事情,或者在两者都适用的情况下抛出异常。
最佳答案
我找到了the answer并将我自己的问题标记为重复。
ZoneId zoneId = ZoneId.of("America/Chicago"); LocalDateTime ldt = LocalDateTime.of(2017, 3, 12, 2, 39, 0, 0); ZoneOffset zoneOffset = zoneId.getRules().getOffset(ldt); ZonedDateTime zdt = ZonedDateTime.ofStrict(ldt, zoneOffset, zoneId);
would throw
Exception in thread "main" java.time.DateTimeException: LocalDateTime '2017-03-12T02:39' does not exist in zone 'America/Chicago' due to a gap in the local time-line, typically caused by daylight savings at java.time.ZonedDateTime.ofStrict(ZonedDateTime.java:484)
关于java - 如果时区的日期时间不明确,是否抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54855891/