Dates and Java suck

Or there must be something I don’t understand. Update: Dates and Java don’t suck.

I need to do some date arithmetic (add an hour to the current time) and submit that as a Date Object to an API method (that as far as I can tell totally neglects the Date Object’s time zone component—and that I have no control over) that sends that data to a server on the east coast.

Here’s my test program:

import java.util.*;

public class MyTest
{
  public static void main(String[] args)
  {
    TimeZone tz = TimeZone.getTimeZone("America/New_York");
    Calendar current_date_cal = Calendar.getInstance(tz);
    Date start = current_date_cal.getTime();

    System.out.println(current_date_cal.get(Calendar.HOUR_OF_DAY));
    System.out.println(start.toString());
  }
}

Running this at 5:00PM PDT (GMT -7) yields the following output:

jwatt@jwatt:~$ java MyTest
20
Thu May 31 16:00:09 GMT-08:00 2007

The Calendar object returns the EST (GMT -5) hour when I’d really rather it be EDT (GMT -4), and the Calendar returns a date object in a different timezone than the Timezone I specified—my current time, sort of, PST, instead of PDT. Of course when a time of 16:00 (5PM pacific time) gets to NY, they say “Silly Wabbit, 5PM already happened!”

relatedposts

3 comments

name
blog (optional)
comment

Consider:

import java.text.DateFormat;
import java.util.Date;
import java.util.TimeZone;

public class MyTest
{
  public static void main(String[] args)
  {
    TimeZone tz = TimeZone.getTimeZone("America/New_York");
    Date start = new Date();
    DateFormat df = DateFormat.getDateTimeInstance();
    df.setTimeZone(tz);
    System.out.println(df.format(start));
  }
}

Running this at 9:02PM CDT (GMT -5) yields:
May 31, 2007 10:02:30 PM

I should be more clear, the System.outs are just there for debugging. It’s a date object I need to pass to a method of an API object. So it’s not so much that I need to format the output, as I need the receiving system to accept the date (one hour in the future) regardless of the timezone of the server I’m sending it from.

My original hunch is that the receiving system is somehow neglecting the timezone—though the more I think about this (now that I have the time to do so), it occurs to me that a Date is usually just stored as the number of seconds since Jan 1, 1970 GMT. Thus timezones are merely formatting overlays on that integer. A date is a date is a date. If you change the time zone, the internal representation in seconds doesn’t change. I think.

All this to say, I’m not sure where the bug is, and it most certainly isn’t Java Date/Calendar implementation.

Your are correct, all date values are internally in GMT. Any timezone you use is for formatting purposes only. The hour of day, and all other similar fields are also based on the requested timezone…