[英]java.util.Date returning different dates in JDK 5 and JDK 6
The below code when run with JDK5(1.5.0_09) prints 当与JDK5(1.5.0_09)运行时,以下代码
Fri May 03 00:00:00 GMT 3912
5/3/12 5:30 AM
and when run with JDK6(1.6.0_23) prints 并与JDK6(1.6.0_23)一起运行时
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. 显然,差异是由于所使用的时区,然后创建了Date对象。 But doesn't this cause problems for existing code when the JDK is upgraded? 但这在JDK升级时是否会对现有代码造成问题? 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 3192
is arising because that deprecated Date
constructor assumes you are using a 2-digit year with 0
meaning 1900
. 出现奇怪的年份3192
是因为不推荐使用的 Date
构造函数假定您使用的是2位数的年份,而0
表示1900
。 It adds 1900
to the year number. 它将1900
添加到年份中。
The difference in the timezones is not the fault of the Date
constructor. 时区的差异不是Date
构造函数的错误。 Your code is using TimeZone.getTimeZone("Asia/Calcutta")
to get the timezone. 您的代码使用TimeZone.getTimeZone("Asia/Calcutta")
获取时区。 That method is documented as returning the GMT timezone if it doesn't recognize the timezone string. 如果该方法无法识别时区字符串,则记录为返回GMT时区。 It would appear that Sun ADDED support for more timezones in Java 1.6. 看起来Sun ADDED在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. 我还没有尝试过,但是当您的请求区域ID无法识别时,以下内容足以防止使用GMT。
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
will understand all of your timezone Strings, and this is clearly not the case for Java 1.5. 假设 getTimeZone
将理解您所有的时区字符串,而Java 1.5显然不是这种情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.