Skip to content

Commit df120f9

Browse files
authored
Merge pull request giantray#57 from gaoshihang/patch-2
Create why-is-subtracting-these-two-times-in-1927-giving-a-strange-re…
2 parents 9eafdcb + bbe5225 commit df120f9

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
##为什么这两个时间(1927年)相减会得到一个奇怪的结果?
2+
3+
###问题描述
4+
如果我运行如下的程序,将两个相距一秒的日期解析成字符串并比较他们。
5+
```
6+
public static void main(String[] args) throws ParseException {
7+
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
8+
String str3 = "1927-12-31 23:54:07";
9+
String str4 = "1927-12-31 23:54:08";
10+
Date sDt3 = sf.parse(str3);
11+
Date sDt4 = sf.parse(str4);
12+
long ld3 = sDt3.getTime() /1000;
13+
long ld4 = sDt4.getTime() /1000;
14+
System.out.println(ld4-ld3);
15+
}
16+
```
17+
18+
输出结果为:
19+
```
20+
353
21+
```
22+
23+
为什么`ld4-ld3`不是`1`(正如我所期望的那样),而是`353`?
24+
25+
如果我把时间改变为之后的一秒:
26+
```
27+
String str3 = "1927-12-31 23:54:08";
28+
String str4 = "1927-12-31 23:54:09";
29+
```
30+
31+
这时,`ld4-ld3`的结果为`1`.
32+
33+
java版本:
34+
```
35+
java version "1.6.0_22"
36+
Java(TM) SE Runtime Environment (build 1.6.0_22-b04)
37+
Dynamic Code Evolution Client VM (build 0.2-b02-internal, 19.0-b04-internal, mixed mode)
38+
```
39+
40+
时区:
41+
```
42+
sun.util.calendar.ZoneInfo[id="Asia/Shanghai",
43+
offset=28800000,dstSavings=0,
44+
useDaylight=false,
45+
transitions=19,
46+
lastRule=null]
47+
48+
Locale(Locale.getDefault()): zh_CN
49+
```
50+
51+
###问题回答
52+
这是因为1927年11月31日上海的时区改变了。
53+
观看[此页](http://www.timeanddate.com/time/change/china/shanghai?year=1927)获得更多关于上海1927年的细节。
54+
这个问题主要是由于在1927年12月31日的午夜,时钟回调了5分钟零52秒。
55+
所以"1927-12-31 23:54:08"这个时间实际上发生了两次,看上去java将这个时间解析为之后的那个瞬间。
56+
因此出现了这种差别。
57+
58+
这只是美好但奇怪的世界时区中的一个插曲。
59+
60+
stackoverflow链接:[Why is subtracting these two times (in 1927) giving a strange result?](http://stackoverflow.com/questions/6841333/why-is-subtracting-these-two-times-in-1927-giving-a-strange-result)

0 commit comments

Comments
 (0)