Aaron Digulla
Aaron Digulla

Reputation: 328790

new Date(long) gives different results

When I run this code:

System.out.println( "XXX date=" + new Date( 1311781583373L ) );

I get this result in Eclipse's JUnit runner:

XXX date=Wed Jul 27 16:46:23 GMT+01:00 2011

and this result in Maven from the command line:

XXX date=Wed Jul 27 17:46:23 CEST 2011

As you can see, the hour is different.

(same computer, same Java version, maybe 30s apart). Why?

[EDIT] Also the time zone is different. Why is Java using CEST when it's started from Maven and GMT+01:00 when started from Eclipse?

Or to put it another way: How can I force Java to use either?

Upvotes: 11

Views: 4812

Answers (3)

Mike Tunnicliffe
Mike Tunnicliffe

Reputation: 10772

To specify the default timezone you can set the system property user.timezone. You can do this by passing it as an argument to the JavaVM (you may need to modify eclipse.ini or Maven equivalent config file):

-Duser.timezone=<your preferred timezone>

...or by setting it programmatically:

 System.setProperty("user.timezone", "<your preferred timezone>");

Or, if it is convenient you can specify a timezone which you use each time you print out the date:

DateFormat myDateFormat = new SimpleDateFormat("<insert date format string here>");    
myDateFormat.setTimeZone(TimeZone.getTimeZone("<your preferred timezone>")); 
....
System.out.println(myDateFormat.format(yourDate));

Upvotes: 5

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340973

Add:

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

before calculating the date. It should display different time zones. And the default time zone is based on the locale your JVM uses. You can force the JVM to use the locale of your preference by supplying it with the following parameters:

$ java -Duser.language=fr -Duser.country=CA

In Maven you can use MAVEN_OPTS environment variable. Also here is an article describing how to change your locale permanently on Windows.

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1503419

Looks like Maven and Eclipse have picked up different default time zones, that's all.

Don't forget that Date.toString() uses the default time zone. I would personally prefer to use Joda Time and probably log the UTC value instead of a local time :)

Upvotes: 6

Related Questions