Got a strange weirdness when using Date
s 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?
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.
Add this line before calling cal.getTime()
:
cal.set(Calendar.MILLISECOND, 0);
This will make sure you set the milliseconds to zero.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With