Varun
Varun

Reputation: 1004

java.util.Date returning different dates in JDK 5 and JDK 6

The below code when run with JDK5(1.5.0_09) prints

Fri May 03 00:00:00 GMT 3912 
5/3/12 5:30 AM

and when run with JDK6(1.6.0_23) prints

Fri May 03 00:00:00 IST 3912
5/3/12 12:00 AM

Obviously the difference is because of the timezone used then the Date object is created. But doesn't this cause problems for existing code when the JDK is upgraded? Is this behavior documented somewhere or am I missing something?

    class TimeTest {

    public static void main(String[] args) {

        Date d = new Date(2012, 04, 3);
        Locale l = new Locale("en", "US","");   
        DateFormat df= DateFormat.getDateTimeInstance(DateFormat.SHORT,  DateFormat.SHORT, l );
        TimeZone t = TimeZone.getTimeZone("Asia/Calcutta");
        df.setTimeZone(t);      
        System.out.println(d);
        System.out.println(df.format(d));

    }
}

Upvotes: 0

Views: 2222

Answers (1)

Stephen C
Stephen C

Reputation: 719239

The strange year 3192 is arising because that deprecated Date constructor assumes you are using a 2-digit year with 0 meaning 1900. It adds 1900 to the year number.

The difference in the timezones is not the fault of the Date constructor. Your code is using TimeZone.getTimeZone("Asia/Calcutta") to get the timezone. That method is documented as returning the GMT timezone if it doesn't recognize the timezone string. It would appear that Sun ADDED support for more timezones in Java 1.6. (Most people would view this as a good thing rather than as a portability concern.)

I haven't tried it, but the following should be sufficient to insulate yourself against using GMT when your requested zone id is unrecognised.

    public TimeZone getZone(String id) {
        TimeZone tz = TimeZone.getTimeZone();
        if (!tz.getID().equals(id)) {
            throw new IllegalArgumentException("unrecognized zone " + id);
        }
        return tz;
    }    

In summary, your code is broken in two respects:

  • It is using a deprecated constructor.
  • It is assuming that getTimeZone will understand all of your timezone Strings, and this is clearly not the case for Java 1.5.

Upvotes: 4

Related Questions