Java Date 类的一个神级误差

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

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

 

Java代码   收藏代码
  1. public static void main(String[] args) throws ParseException {  
  2.     SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    
  3.     String str3 = "1927-12-31 23:54:07";    
  4.     String str4 = "1927-12-31 23:54:08";    
  5.     Date sDt3 = sf.parse(str3);    
  6.     Date sDt4 = sf.parse(str4);    
  7.     long ld3 = sDt3.getTime() /1000;    
  8.     long ld4 = sDt4.getTime() /1000;   
  9.     System.out.println(ld3);    
  10.     System.out.println(ld4);    
  11.     System.out.println(ld4-ld3);  
  12. }  

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

 

Java代码   收藏代码
  1. -1325491905  
  2. -1325491552  
  3. 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 对这一时间的解析采用了“晚点”的本地时间实现,用以区分。

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

 

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值