I found out that different computer return different result from the following statement in Java.
private static final Date ORIGIN = new Date(0L);
In my computer, it return the following result.
Wed Dec 31 16:00:00 PST 1969
But that's different from what it supposed to. I am thinking it should return the following result
Thu Jan 1 16:00:00 PST 1970
How can I ensure the date is the same between different compute开发者_如何学JAVAr? What's the best practice? Thanks.
The Date
is actually exactly the same. The difference is only in how it's formatted by its toString()
method - that depends on the default Locale
and timezone of the computer (and the timezone data in turn can depend on the Java version).
To get a consistent output, use a SimpleDateFormat
with a fixed pattern and a fixed timezone (in some rare cases it can still differ because of changed timezone data).
And 32/64 bits has nothing to do with it either.
If you want to set an epoch date yourself instead of directly using 0L, you may do sth similar to below. This way it will return different number in different timezones
Calendar epoch = Calendar.getInstance();
epoch.set(Calendar.YEAR, 1900);
epoch.set(Calendar.MONTH, Calendar.JANUARY);
epoch.set(Calendar.DAY_OF_MONTH, 0);
epoch.set(Calendar.HOUR_OF_DAY, 0);
epoch.set(Calendar.MINUTE, 0);
epoch.set(Calendar.SECOND,0);
epoch.set(Calendar.MILLISECOND, 0);
Date d = epoch.getTime();
However, javadoc for Date says ; "A milliseconds value represents the number of milliseconds that have passed since January 1, 1970 00:00:00.000 GMT
." So it is gonna do same thing when you do new Date(0L);
精彩评论