在java中将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) 将那天转换为 LocalDateTime 表示 0 小时 1 分钟的时间,即当天的 00:01,仍然没有任何时区。

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

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