java.util.Date在JDK 5和JDK 6中返回不同的日期 [英] java.util.Date returning different dates in JDK 5 and JDK 6

查看:147
本文介绍了java.util.Date在JDK 5和JDK 6中返回不同的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用JDK5(1.5.0_09)运行时,以下代码打印

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

当运行JDK6(1.6。 0_23)打印

and when run with JDK6(1.6.0_23) prints

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

显然,区别是因为时区使用了Date对象被创建。但是,当JDK升级时,这不会造成现有代码的问题吗?这个行为记录在某个地方,还是我错过了什么?

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

    }
}


推荐答案

奇怪的一年 3192 是因为不推荐使用 Date 构造函数假定您是使用2位数的年份与 0 意味着 1900 。它向年号增加了 1900

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.

时区的区别不在于 Date 构造函数。您的代码正在使用 TimeZone.getTimeZone(亚洲/加尔各答)获取时区。该方法是记录的返回GMT时区,如果它不识别时区字符串。看来Sun ADDED支持Java 1.6中的更多时区。 (大多数人会认为这是一件好事,而不是可移植性的关注。)

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

我没有尝试过,但以下内容应该足以使自己与当您请求的区域ID无法识别时,使用GMT。

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:


  • 它正在使用不推荐的构造函数。

  • 假设 getTimeZone 将了解所有的时区字符串,这显然不是Java 1.5。

  • 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.

这篇关于java.util.Date在JDK 5和JDK 6中返回不同的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆