views:

709

answers:

4

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?

+1  A: 

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.

Brian Agnew
A: 

See http://java.sun.com/j2se/1.4.2/docs/api/java/util/Date.html#toString%28%29.

Yes, it's using timezones. It should also print them out (the three characters before the year).

svens
A: 

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.

Michael Borgwardt
A: 

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.

John M