始终在UTC时区下运行Java应用程序

3
以下两种方法是否完全等效,以确保 Java 应用程序在 UTC 中运行?
  1. Starting the JVM with the 'user.timezone' parameter:

    java -jar MyJar.jar -Duser.timezone=UTC
    
  2. Having the following method executed from the main() method (Java 8)

    private static void setUtcTimezone() {
        ZoneId zoneId = ZoneId.of("UTC");
        TimeZone zone = TimeZone.getTimeZone(zoneId);
        TimeZone.setDefault(zone);
    }
    

我希望让应用程序在UTC时间下运行,不再提供可选项,因此不建议使用JVM参数方法。

1个回答

1
没有任何迹象表明这两种方法不等价。唯一的区别在于变体1在进入main()之前设置了默认时区。
因此,在调用setUtcTimezone()之后,它们两者是等价的,但在此之前不是。 理论上,您可以有一个静态初始化程序在main被调用之前使用时区。
但这由您负责。

There are no pitfalls using variant 2, use it, it will work.

I use this approach which is a bit shorter.

 TimeZone.setDefault(TimeZone.getTimeZone("UTC"));

The only weak point in both variants, is trusting that no other code changes the default time zone. So it is a good idea for specific method that should use UTC in e.g Date formatting to use a DateFormater (not static, either an instance or using Thread.Local()) and explicitly set the TimeZone UTC to that formatter. This then is save to output or calculate in UTC.


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接