Why is subtracting these two times (in 1927) giving a strange result?

前端 未结 10 1093
既然无缘
既然无缘 2020-11-21 08:10

If I run the following program, which parses two date strings referencing times 1 second apart and compares them:

public static void main(String[] args) throw         


        
10条回答
  •  [愿得一人]
    2020-11-21 08:47

    This happens because that's the timezone rules for the year 31st DEC 1927 in Shanghai. If you go to this page and choose "Time zone changes for 1900 - 1924", you'll see that in 1900 the date and time are "UTC +8:05:43 hours all of the period".

    So Java is just showing the time configured for that timezone, at that year.

    if you change your default timezone to Hong Kong it will show correct results.

    TimeZone.setDefault(TimeZone.getTimeZone("Asia/Hong_Kong"));
    

    Note that the timezone changed from CST (China Standard Time, the "3-letter equivalent" to Asia/Shanghai) to HKT (the 3-letter name for Hong Kong's timezone).

    But changing time zone is not good solution. So instead use system UTC time whenever possible. It will always give local time after conversion.

提交回复
热议问题