在爪哇中将UTC时间转换为欧洲/伦敦时区



我当前有UTC的日期时间,但我需要时区(欧洲/伦敦)的日期时间。我试过了,但每次时间都没有添加,而是在当前日期时间附加此偏移量。

我的代码 -

LocalDateTime utcTime = LocalDate.now().atTime(0,1);
System.out.println("utc time " + utcTime);
ZoneId europeLondonTimeZone = ZoneId.of("Europe/London");
ZoneOffset offset = europeLondonTimeZone.getRules().getOffset(utcTime);
OffsetDateTime offsetDateTime = utcTime.atOffset(offset);
System.out.println(offsetDateTime);

它将打印:

"2021-06-18T00:01+01:00"

但我想

"2021-06-17T23:01"

因为 +01:00 在夏令时领先。

谢谢

如果您只想要英国的当前时间,则无需从 UTC 转换。你可以直接拥有那个时间。

ZoneId europeLondonTimeZone = ZoneId.of("Europe/London");
OffsetDateTime offsetDateTime = OffsetDateTime.now(europeLondonTimeZone);
System.out.println(offsetDateTime);

我刚才运行代码时的输出:

2021-06-18T19:18:39.599+01:00

如果您确实需要先使用 UTC 时间,请避免为此使用LocalDateLocalDateTime。某些 java.time 类名中的local表示没有时区或 UTC 偏移量。首选OffsetDateTime,顾名思义,它本身会跟踪其偏移量。因此,当它处于UTC时,它本身就"知道"了这个事实。

// Sample UTC time
OffsetDateTime utcTime = OffsetDateTime.now(ZoneOffset.UTC);
System.out.println("UTC time: " + utcTime);
ZoneId europeLondonTimeZone = ZoneId.of("Europe/London");
OffsetDateTime offsetDateTime = utcTime.atZoneSameInstant(europeLondonTimeZone)
.toOffsetDateTime();
System.out.println("UK time:  " + offsetDateTime);
UTC time: 2021-06-18T18:18:39.669Z
UK time:  2021-06-18T19:18:39.669+01:00

atZoneSameInstant方法从OffsetDateTime所在的任何偏移量(在本例中为 UTC)转换为作为参数传递的时区,因此通常会更改时钟时间(有时甚至是日期)。

您的代码中出了什么问题?

LocalDate只包含一个没有时间的日期,因此LocalDate.now()只提供它在 JVM 的默认时区中的哪一天(所以甚至不是 UTC 中的哪一天),而不是一天中的时间。.atTime(0,1)将该天转换为表示当天 0 小时 1 分钟(即 00:01)时间的LocalDateTime,仍然没有任何时区。

此外,ZonedDateTime不仅知道其时区,还可以处理其时区规则。因此,您没有理由自己处理特定时间的偏移量。

最后,LocalDateTime.atOffset()转换为OffsetDateTime,但既不更改日期,也不更改一天中的时间。由于LocalDateTime没有任何时区,因此该方法不能用于在时区之间进行转换。

最新更新