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

风格不统一 提交于 2019-12-25 08:46:38

问题


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));

    }
}

回答1:


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.


来源:https://stackoverflow.com/questions/10481122/java-util-date-returning-different-dates-in-jdk-5-and-jdk-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!