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));
}
}
The strange year
3192is arising because that deprecatedDateconstructor assumes you are using a 2-digit year with0meaning1900. It adds1900to the year number.The difference in the timezones is not the fault of the
Dateconstructor. Your code is usingTimeZone.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.
In summary, your code is broken in two respects:
getTimeZonewill understand all of your timezone Strings, and this is clearly not the case for Java 1.5.