Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

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

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) 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(ld4-ld3);
}


The output is:*
353


Why is ld4-ld3, not 1 (as I would expect from the one-second difference in the times), but 353?

If I change the dates to times 1 second later:
String str3 = "1927-12-31 23:54:08";  
String str4 = "1927-12-31 23:54:09";


Then ld4-ld3 will be 1.
*Java version:

java version "1.6.0_22"
Java(TM) SE Runtime Environment (build 1.6.0_22-b04)
Dynamic Code Evolution Client VM (build 0.2-b02-internal, 19.0-b04-internal, mixed mode)
Timezone(`TimeZone.getDefault()`):

sun.util.calendar.ZoneInfo[id="Asia/Shanghai",
offset=28800000,dstSavings=0,
useDaylight=false,
transitions=19,
lastRule=null]

Locale(Locale.getDefault()): zh_CN
by

2 Answers

akshay1995
Instead of converting each date, you can use the following code:

long difference = (sDt4.getTime() - sDt3.getTime()) / 1000;
System.out.println(difference);

And then see that the result is:

1
sandhya6gczb
it's a time change in 1927 in Shanghai.

It was 23:54:07 in Shanghai, in the local standard time, but then after 5 minutes and 52 seconds, it turned to the next day at 00:00:00, and then local standard time changed back to 23:54:08. So, that's why the difference between the two times is 343 seconds, not 1 second, as you would have expected.

The time can also mess up in other places like the US. The US has Daylight Saving Time. When the Daylight Saving Time starts the time goes forward 1 hour. But after a while, the Daylight Saving Time ends, and it goes backward 1 hour back to the standard time zone. So sometimes when comparing times in the US the difference is about 3600 seconds not 1 second.

But there is something different about these two-time changes. The latter changes continuously and the former was just a change. It didn't change back or change again by the same amount.

It's better to use UTC unless if needed to use non-UTC time like in display.

Login / Signup to Answer the Question.