Thursday, August 14, 2008
Dating with JAVA
Programatically in JAVA a Date object is nothing but a long value that holds the number of milliseconds since January 1, 1970, 00:00:00 GMT.
So new Date() on Aug 14 13:53:58 EST 2008 would be the same as Aug 14 10:53:58 PST 2008 = 1218740038000 (precise to the last 3 digits).
So how are those two different? TimeZoneOffset.
This is an int value that gives millisecs difference between GMT and the Specified TimeZone.
So When printing/displaying or getting the value of date in TimeZone, this timezone offset is added to the long utc secs.
This gives the new print value (or display value - Aug 14 13:53:58 EST 2008 ).
The display value includes all calculations for Timezone and is meaningfully correct only when displayed with the Timezone information (as above).
Just reading and writing "yyyy-MM-dd hh:mm:ss" is incorrect.
A count of the number of milliseconds since the standard base time known as "The Epoch", namely January 1, 1970, 00:00:00 GMT as stated above.
You cannot convert a Date into a different time zone, but you can use Java's DateFormat class to format a Date into the time zone you want.
Simplifying it , let Date do what it does and when you're ready to display or print out a String representation of Date, that's when you tell DateFormat what time zone you want it in.
So, here's some code that shows it:
final Date currentTime = new Date();
final SimpleDateFormat sdf =
new SimpleDateFormat("EEE, MMM d, yyyy hh:mm:ss a z");
// Give it to me in US-Pacific time.
sdf.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
System.out.println("LA time: " + sdf.format(currentTime));
Dating without a Date. -S
Subscribe to:
Posts (Atom)