Reputation: 23186
I have the following code which is supposed to reset the given time in milliseconds to midnight of the same day. I have two time instances, 1409097600000l and 1409270400000l, both of which are already at midnight. However, after passing through the reset code, one comes out untouched, while the other ends up in the previous day (-86400000). I am wondering if someone could explain what is going on. Here is my code:
Calendar start = Calendar.getInstance();
start.setTimeZone(TimeZone.getTimeZone("UTC"));
start.setTime(new Date(1409097600000l));
// reset hour, minutes, seconds and millis
start.set(Calendar.HOUR_OF_DAY, 0);
start.set(Calendar.MINUTE, 0);
start.set(Calendar.SECOND, 0);
start.set(Calendar.MILLISECOND, 0);
System.out.println("All Day Start: " + start.getTimeInMillis());
Calendar end = Calendar.getInstance();
end.setTime(new Date(1409270400000l));
System.out.println("1: " + end.getTimeInMillis());
end.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println("2: " + end.getTimeInMillis());
// reset hour, minutes, seconds and millis
end.set(Calendar.HOUR_OF_DAY, 0);
end.set(Calendar.MINUTE, 0);
end.set(Calendar.SECOND, 0);
end.set(Calendar.MILLISECOND, 0);
System.out.println("All Day End: " + (end.getTimeInMillis()));
The output on my machine is:
All Day Start: 1409097600000
1: 1409270400000
2: 1409270400000
All Day End: 1409184000000
Upvotes: 2
Views: 277
Reputation: 339362
The accepted answer is correct. But you have other issues.
The old bundled classes java.util.Date and .Calendar are notoriously troublesome. Avoid them. They really are that bad. Instead use either the venerable Joda-Time library or the new java.time package now bundled with Java 8 (inspired by Joda-Time).
Your code assumes the first moment of the day is midnight, meaning 00:00:00
. Not always true because of Daylight Saving Time or other anomalies. For UTC it is always true, granted. Nevertheless, I suggest making a habit of calling the withTimeAtStartOfDay
method in Joda-Time.
Tip: Using an uppercase L
rather than a lowercase one in your long
literal avoids confusion with the digit 1
.
Joda-Time offers three classes to handle a span of time such as you have here in this question: Interval, Period, and Duration.
This work is simpler in Joda-Time.
long startLong = 1409097600000L;
long stopLong = 1409270400000L;
DateTime start = new DateTime( startLong , DateTimeZone.UTC );
DateTime start2 = start.withTimeAtStartOfDay();
DateTime stop = new DateTime( stopLong , DateTimeZone.UTC );
DateTime stop2 = stop.withTimeAtStartOfDay();
Interval interval = new Interval( start2 , stop2 );
Upvotes: 1
Reputation: 1074979
You're setting the timezone of the second calendar after setting its time. So you're setting the time in the default timezone (presumably your local one). Then you change the time zone, which apparently puts it sometime yesterday.
Move the setTimeZone
line in the second instance up, just like you have it in the first instance.
Upvotes: 3