Thursday, September 23, 2010

Not the timezones you are looking for

Probably purely by coincidence I have recently been asked repeatedly about Java Date values changing when in fact the only difference is how the value was formatted for display.

For example, why did the date change here?

2010-09-23 17:27:54,565 DEBUG [SomeClass] start date Thu Sep 09 00:00:00 UTC 2010 
2010-09-23 10:44:24,728 DEBUG [SomeClass] start date Wed Sep 08 17:00:00 PDT 2010

At a glance it looks like the date isn't the same: it isn't the same day, hour, or timezone!

The answer is the first line of the Date class javadoc:
"The class Date represents a specific instant in time, with millisecond precision." (see here)
Note that it does NOT have a timezone. A timezone is applied only when formatting the date. We can even prove the date hasn't changed:

import static org.junit.Assert.assertEquals;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.junit.Test;

public class DateTzTest {
 public void dateCompare() throws ParseException {
  DateFormat df = new SimpleDateFormat("EEE MMM dd hh:mm:ss z yyyy");
  Date d1 =  df.parse("Thu Sep 09 00:00:00 UTC 2010");
  Date d2 =  df.parse("Wed Sep 08 17:00:00 PDT 2010");
  assertEquals(d1.getTime(), d2.getTime());

No comments:

Post a Comment