gpt4 book ai didi

java - Jboss Java Date 夏令时

转载 作者:行者123 更新时间:2023-12-01 17:56:27 25 4
gpt4 key购买 nike

有一个问题,当时钟由于夏令时(每年两次)而移动时,Java 中的日期不正确(我位于中欧:夏季 GMT+2 ,冬季GMT+1)

如果时间提前 1 小时,new Date() 仍返回旧时间(比当前时间晚 1 小时)。

在 Java 7 中,可以在不重新启动 Jboss 应用服务器的情况下解决这个问题吗?

如果我在 Windows 中手动更改时间,则会重现问题:除非重新启动 jboss,否则 Date 不会更新为系统日期。

Calendar c = Calendar.getInstance();
c.setTime(new Date());

最佳答案

Java <= 7中,您可以使用ThreeTen Backport ,Java 8 新日期/时间类的一个很好的向后移植。

有了这个,您可以轻松处理夏令时更改。

首先,您可以使用 org. Threeten.bp.DateTimeUtilsCalendar 之间进行转换。

以下代码将 Calendar 转换为 org. Threeten.bp.Instant,这是一个表示“UTC 时刻”(独立于时区的时间戳)的类:现在,此时此刻,世界上的每个人都处于同一时刻,尽管他们的本地日期和时间可能会有所不同,具体取决于他们所在的位置)。

然后,Instant 被转换为 org. Threeten.bp.ZonedDateTime (这意味着:在这一瞬间,这个时区的日期和时间是多少? )。我还使用 org. Threeten.bp.ZoneId 来获取时区:

Calendar c = Calendar.getInstance();
c.setTime(new Date());

// get the current instant in UTC timestamp
Instant now = DateTimeUtils.toInstant(c);

// convert to some timezone
ZonedDateTime z = now.atZone(ZoneId.of("Europe/Berlin"));

// today is 08/06/2017, so Berlin is in DST (GMT+2)
System.out.println(z); // 2017-06-08T14:11:58.608+02:00[Europe/Berlin]

// testing with a date in January (not in DST, GMT+1)
System.out.println(z.withMonth(1)); // 2017-01-08T14:11:58.608+01:00[Europe/Berlin]

我刚刚选择了一些使用中欧时区 (Europe/Berlin) 的时区:您不能使用这些 3 字母缩写,因为它们是 ambiguous and not standard 。您可以将代码更改为最适合您系统的时区(您可以使用 ZoneId.getAvailableZoneIds() 获取所有可用时区的列表)。

我更喜欢这个解决方案,因为它明确了我们用来向用户显示的时区(DateCalendartoString() 方法在幕后使用默认时区,你永远不知道它们在做什么)。

在内部,我们可以继续使用 UTC 格式的 Instant,因此它不受时区的影响(并且您可以随时在需要时在时区之间进行转换) - 如果您愿意的话将 ZonedDateTime 转换回 Instant,只需使用 toInstant() 方法即可。

<小时/>

实际上,如果您想获取当前日期/时间,只需忘记旧的类(DateCalendar)并仅使用 Instant:

// get the current instant in UTC timestamp
Instant now = Instant.now();

但是如果您仍然需要使用旧的类,只需使用 DateTimeUtils 进行转换即可。

<小时/>

上述示例的输出是 ZonedDateTime.toString() 方法的结果。如果您想更改格式,请使用 org. Threeten.bp.format.DateTimeFormatter 类(有关所有可能格式的更多详细信息,请查看 javadoc):

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss z X");
// DST (GMT+02)
System.out.println(formatter.format(z)); // 08/06/2017 14:11:58 CEST +02
// not DST (GMT+01)
System.out.println(formatter.format(z.withMonth(1))); // 08/01/2017 14:11:58 CET +01

关于java - Jboss Java Date 夏令时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44434167/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com