Collin Peters
Collin Peters

Reputation: 4643

Always run Java app in UTC

Are the following two methods exactly equivalent to make sure that the Java app is running in 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);
    }
    

I am wanting to make it non-optional that the app runs in UTC so the JVM argument method is not desirable.

Upvotes: 3

Views: 2604

Answers (1)

AlexWien
AlexWien

Reputation: 28747

There are no hints that these two approaches are not equivalent. The only difference is that variant 1 sets the default timezone before entering the main().

So after setUtcTimezone() is called they both variants are equivalent, before not. Theretically you could have an static initializer which uses the TimeZone before main is called.

But this then is in your responsibility.

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.

Upvotes: 1

Related Questions