【问题标题】:Convert UTC time to Europe/London timezone in java在java中将UTC时间转换为欧洲/伦敦时区
【发布时间】:2021-06-18 07:50:56
【问题描述】:

我有 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 早于夏令时。

谢谢

【问题讨论】:

标签: java spring-boot datetime localdatetime


【解决方案1】:

如果您只需要英国的当前时间,则无需从 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没有任何时区,所以该方法不能用于时区之间的转换。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-12
    • 1970-01-01
    • 2013-05-29
    • 2021-07-20
    • 1970-01-01
    相关资源
    最近更新 更多