Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysterious milliseconds number found in Java Date/Calendar object

Got a strange weirdness when using Dates and Calendar. Point is I want to create a specific date e.g.

Calendar cal = Calendar.getInstance();
cal.set(1970, 0, 1, 0, 0, 0);
Date date = cal.getTime(); 

Now the thing is: it shows the correct date, but when debugging I see under the date-variable a "fasttime" of e.g. -3599459. This makes my JUnit tests fail, because the expected value is -3600000. It seems the Calendar adds 541 milliseconds or something like when initializing...

Question is: is it not possible to simply create a fixed date without this 'i'm adding some milliseconds in the background'-ghost function?

like image 853
Malvin Avatar asked Nov 13 '12 09:11

Malvin


2 Answers

From the docs for the set method you're calling:

Sets the values for the fields YEAR, MONTH, DAY_OF_MONTH, HOUR, MINUTE, and SECOND. Previous values of other fields are retained. If this is not desired, call clear() first.

So it's retaining the millisecond value. It's not adding some milliseconds - it's taking the system time when you call getInstance, as it's documented to do.

Call clear() first, or explicitly set the millisecond value. (Personally I'd use clear(). I'd also explicitly set the time zone, just to make it clearer which time you're expecting.

Alternatively, use Joda Time to start with - it's a much more pleasant date/time API.

like image 130
Jon Skeet Avatar answered Nov 04 '22 00:11

Jon Skeet


Add this line before calling cal.getTime():

cal.set(Calendar.MILLISECOND, 0);

This will make sure you set the milliseconds to zero.

like image 28
Dan D. Avatar answered Nov 04 '22 02:11

Dan D.