I set my Calendar instance to a UTC date at 00:00 however once i return the result its 1 hour ahead
Calendar cal = Calendar.getInstance(TIMEZONE_UTC, Locale.ENGLISH);
cal.set(2017, 12 - 1, 15);
cal.set(Calendar.AM_PM, Calendar.AM);
cal.set(Calendar.HOUR, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
System.out.println(cal.getTime());
// Fri Dec 15 01:00:00 CET 2017 but should be 00:00:00
I suppose there is the winter/summer offset but I didn't found any description in the Gregorian or Calendar Element to handle this issue
I am getting the impression that you are really after just the date of December 15, 2017, and just wanted to make sure that there is no unexpected hour-of-day? If so,
LocalDate
fromjava.time
, the modern Java date and time API, is made for you:This prints
No hours, minutes or seconds to be concerned about.
If you do need a date-time at 00:00 UTC (the time I used to call midnight until Basil Bourque’s comment), there are several ways to obtain it. One of them is:
This prints
The
Z
in the end means UTC or offset zero. You see that the time of day is 00:00 as you wanted.The
Calendar
class that you used in the question is long outdated, so I recommend you don’t use it anymore.java.time
, the modern Java date and time API also known as JSR-310, is so much nicer to work with.What went wrong in your code?
While a
Calendar
does contain a time zone (you initialized it toTIMEZONE_UTC
), aDate
(another outdated class) doesn’t. So when you convert toDate
usingcal.getTime()
you lose the information that you wanted the time to be in UTC. Next (and this confuses many), when you print the date, you implicitly callDate.toString()
, and this method grabs your JVM’s time zone setting and produces a string with the time in this time zone. So apparently you are (like I am) in a time zone that is at UTC+01:00 in December. The following two date-times denote the same point on the timeline: