Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtraction of 1ms leads to unexpected behaviour

What is wrong? I assume that if I subtract 1ms from 1 Jan 1980 0:0:0 then I've got 1979. But I must subtract about 500+ ms for this. Please, give me a hint.

val cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
cal.set(1980, 0, 1, 0, 0, 0)
val date = new Date
date.setTime(cal.getTimeInMillis()) // <- 1980 Jan 01 0:0:0
date.setTime(cal.getTimeInMillis() - 1) // <- 1980 Jan 01 0:0:0 too !!!

Updated.

The solution is

val cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
cal.setTimeInMillis(0)
cal.set(1980, 0, 1, 0, 0, 0)
like image 690
Ezhik Avatar asked Sep 22 '13 17:09

Ezhik


1 Answers

With Calendar.set(year, month, day, hourOfDay, minute, second) no milliseconds are set. Consequently the Calendar implementation sets the milliseconds to "unknown" which is actually treated as the midpoint within the given second.

Subtracting 500ms means you just step over the midpoint. Same should happen if you add 500ms, which should bring you just over the second. Actually subtracting 500ms works and you must add 620ms to see the next second.

like image 171
jboi Avatar answered Oct 25 '22 08:10

jboi