论坛首页 Java企业应用论坛

Java Date 类的一个神级误差

浏览 12604 次
该帖已经被评为隐藏帖
作者 正文
   发表时间:2011-08-22  

源自 Stack Overflow 的一个问题,原文点此外连接

问题很简单,跑如下代码:

 

public static void main(String[] args) throws ParseException {
    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
    String str3 = "1927-12-31 23:54:07";  
    String str4 = "1927-12-31 23:54:08";  
    Date sDt3 = sf.parse(str3);  
    Date sDt4 = sf.parse(str4);  
    long ld3 = sDt3.getTime() /1000;  
    long ld4 = sDt4.getTime() /1000; 
    System.out.println(ld3);  
    System.out.println(ld4);  
    System.out.println(ld4-ld3);
}

 预期 ld4 - ld3 的结果为 1。然后实际结果是:

 

-1325491905
-1325491552
353

即 Java 中 1927年12月31日 23时54分07秒 与 1927年12月31日 23时54分08秒存在 353 秒的误差。

 

导致问题的原因解答如下:

 

 写道
See this page for details of 1927 in Shanghai. Basically at midnight at the end of 1927, the clocks went back 5 minutes and 52 seconds. So "1927-12-31 23:54:08" actually happened twice, and it looks like Java is parsing it as the later possibly instant for that local date/time - hence the difference.

Just another episode in the often weird and wonderful world of time zones.

 写道

此外查看1927年上海时区详情。简单的说在1927年最后一天的午夜,标准时间被回调了5分52秒。所以"1927-12-31 23:54:08"确切地说出现了两次。现在看来,Java 对这一时间的解析采用了“晚点”的本地时间实现,用以区分。

这只是又一个关于时区的神秘而神奇的案例。

 

代码的世界,无奇不有。有些东西,你不知道,你就真的不知道啊。呵呵

   发表时间:2011-08-23  
这个问题的确神奇.不过对一般应用没啥影响.
0 请登录后投票
   发表时间:2011-08-23  
在下发过此贴,被管理同志转到提问里去了 
0 请登录后投票
   发表时间:2011-08-23  
好贴,忍不住,顶了。
0 请登录后投票
   发表时间:2011-08-23  
这才叫严谨
0 请登录后投票
   发表时间:2011-08-23   最后修改:2011-08-23
lqtcts 写道
好贴,忍不住,顶了。


+1

0 请登录后投票
   发表时间:2011-08-23  
这不是神级误差呀,这就是个神级的人物
0 请登录后投票
   发表时间:2011-08-23  
艾斯比越来越多了 你加上时区再看看
0 请登录后投票
   发表时间:2011-08-23  
相当有意思
0 请登录后投票
   发表时间:2011-08-23  
http://coolshell.cn/articles/5075.html
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics