Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java System.getProperty( "user.timezone" ) does not work

When I start java program by java -Duser.timezone="UTC",

System.out.println( System.getProperty( "user.timezone" ) );
System.out.println( new Date() ); // prints time in UTC 

prints UTC time, but when I set in code like:

System.setProperty( "user.timezone", "UTC" );
System.out.println( System.getProperty( "user.timezone" ) );  // prints 'UTC'
System.out.println( new Date() ); // prints time in local zone, not in UTC

does not print time in UTC . I need to set time in code. Not looking for Joda

Environment: JDK 1.6 / Windows XP

Please help. Thanks much!

like image 526
user1418717 Avatar asked Oct 01 '13 17:10

user1418717


1 Answers

Your problem is that earlier, at JVM startup, Java has already set the default timezone, it has called TimeZone.setDefault(...); using the original "user.timezone" property. Just changing the property afterwards with System.setProperty("user.timezone", "UTC") has in itself no effect.

That's why the normal way to set the default timezone at start time is: java -Duser.timezone=...

If you insist on setting the timezone programatically, you can, after changing the property, set the default timezone to null to force its recalculation:

  System.setProperty("user.timezone", "UTC");
  TimeZone.setDefault(null);

(from here).

Or, simpler and cleaner, set it explicity:

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

Be aware of potential issues if running under a SecurityManager.

like image 89
leonbloy Avatar answered Sep 18 '22 10:09

leonbloy