Maharjun M
Maharjun M

Reputation: 923

how to set timezone for jvm through command line

My local machine's timezone is HST. But JVM giving me CUT/UTC timezone. I tried using java -Duser.timezone=America/Adak Example, but it sets HST only for Example.class . How/where can I See/Change the JVM's timezone?

The ZONE value in /etc/sysconfig/clock is pointing to HST timezone only.

class Example {
public static void main(String[] args) {
    System.out.println(java.util.TimeZone.getDefault());
} 
}

The Above code is giving me UTC timezone.

I am using CentOS vagrant box and java 8.

I can Set the Timezone by using java -Duser.timezone=America/Adak

by using above statement we are externally setting the timezone. But we are not taking the Default/machine's timezone.

I am asking how can we get/see/change the system's timezone using java.

Upvotes: 3

Views: 13557

Answers (2)

Basil Bourque
Basil Bourque

Reputation: 338336

See your JVM’s current default time zone by calling ZoneId.systemDefault().

You do not explain what is the default time zone of your host OS (which you have not described) versus that of your Vagrant box. I'm not knowledgeable with running Java containerized but I imagine your Java implementation (which you have not yet described) is picking up its default from either the host OS or the container.

Always specify your desired/expected zone

But here is the thing: You should not care. Your Java programming should never rely implicitly on the JVM’s current default time zone. Your Question itself is evidence for my point.

Instead, always specify a time zone explicitly in your code.

Never rely on default zone

Another reason you should never depend on the default is that it can be changed at any moment during runtime(!) by any code in any thread of any app running within the JVM.

Instead pass your desired/expected time zone as an optional argument.

For example, to get the current moment in a zone:

ZoneId z = ZoneId.of( "America/Adak" );
ZonedDateTime zdt = ZonedDateTime( z );

Look throughout the java.time classes and you'll see that wherever a time zone or offset is relevant you can pass a ZoneId or ZoneOffset object as an optional argument. Personally I believe Java programmers would be better off if those arguments were required rather than optional as so many of us fail to think about the issue of time zone and offset.

Upvotes: 2

Thomas Fritsch
Thomas Fritsch

Reputation: 10127

You can see your JVM's timezone by

System.out.println(TimeZone.getDefault());

You can set it in the JVM call for example by

java -Duser.timezone=HST ...

or programmatically by something like

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

Upvotes: 6

Related Questions