Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 864
Aaron Digulla Avatar asked Aug 08 '11 12:08

Aaron Digulla


3 Answers

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 :)

like image 117
Jon Skeet Avatar answered Nov 02 '22 04:11

Jon Skeet


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));
like image 39
Mike Tunnicliffe Avatar answered Nov 02 '22 05:11

Mike Tunnicliffe


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.

like image 3
Tomasz Nurkiewicz Avatar answered Nov 02 '22 05:11

Tomasz Nurkiewicz