I am using the Calendar class in java and am having trouble. I have this code
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("NZST"));
System.out.println("Calendar.HOUR_OF_DAY = " + calendar.get(Calendar.HOUR_OF_DAY));
System.out.println("Calendar.HOUR = " + calendar.get(Calendar.HOUR));
System.out.println("calendar.getTime() = " + calendar.getTime());
and I would expect it to output
Calendar.HOUR_OF_DAY = 17
Calendar.HOUR = 5
calendar.getTime() = Sat Aug 08 17:45:53 NZST 2020
but instead it outputs
Calendar.HOUR_OF_DAY = 5
Calendar.HOUR = 5
calendar.getTime() = Sat Aug 08 17:45:53 NZST 2020
So why does the HOUR_OF_DAY and HOUR return the same thing however, calendar.getTime() shows the correct HOUR_OF_DAY. They are both using NZST.
They are both using NZST.
No, they're not, although I can see why you think they are.
The first is actually using UTC, because "NZST" is not a valid time zone ID. It's a shame that TimeZone.getTimeZone
doesn't throw an exception when you present it with an invalid ID, but that can't be changed now :(
calendar.getTime()
is returning a Date
reference, and Date
doesn't have a time zone so it's printing in your system local time zone - which happens to be New Zealand.
If you change your first line of code to use a real time zone ID, it behaves as you expect it to:
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("Pacific/Auckland"));
A few abbreviations (like NZST) are recognized as time zone IDs in Java, but it's always better to use the full IANA time zone ID, like "Pacific/Auckland".