Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is java.util.Date using TimeZone?

I have 2 different computers, each with different TimeZone.

In one computer im printing System.currentTimeMillis(), and then prints the following command in both computers: System.out.println(new Date(123456)); --> 123456 stands for the number came in the currentTimeMillis in computer #1.

The second print (though typed hardcoded) result in different prints, in both computers. why is that?

like image 259
Udi Avatar asked Oct 04 '09 11:10

Udi


4 Answers

How about some pedantic detail.

java.util.Date is timezone-independent. Says so right in the javadoc.

You want something with respect to a particular timezone? That's java.util.Calendar.

The tricky part? When you print this stuff (with java.text.DateFormat or a subclass), that involves a Calendar (which involves a timezone). See DateFormat.setTimeZone().

It sure looks (haven't checked the implementation) like java.util.Date.toString() goes through a DateFormat. So even our (mostly) timezone-independent class gets messed up w/ timezones.

Want to get that timezone stuff out of our pure zoneless Date objects? There's Date.toGMTString(). Or you can create your own SimpleDateFormatter and use setTimeZone() to control which zone is used yourself.

like image 51
John M Avatar answered Nov 14 '22 22:11

John M


why is that?

Because something like "Oct 4th 2009, 14:20" is meaningless without knowing the timezone it refers to - which you can most likely see right now, because that's my time as I write this, and it probably differs by several hours from your time even though it's the same moment in time.

Computer timestamps are usually measured in UTC (basically the timezone of Greenwich, England), and the time zone has to be taken into account when formatting them into something human readable.

like image 29
Michael Borgwardt Avatar answered Nov 14 '22 23:11

Michael Borgwardt


Because that milliseconds number is the number of milliseconds past 1/1/1970 UTC. If you then translate to a different timezone, the rendered time will be different.

e.g. 123456 may correspond to midday at Greenwich (UTC). But that will be a different time in New York.

To confirm this, use SimpleDateFormat with a time zone output, and/or change the timezone on the second computer to match the first.

like image 21
Brian Agnew Avatar answered Nov 14 '22 21:11

Brian Agnew


javadoc explains this well, System.currentTimeMillis() Note that while the unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds.

like image 26
engineer Avatar answered Nov 14 '22 21:11

engineer