I'm using the java Calendar to create some date at midnight (GMT), then change the timezone to my local timezone to make sure the requested time would be 1:00 (GMT +1). The code below works, incl. 2 successful asserts.
TimeZone TIMEZONE_GMT = TimeZone.getTimeZone("GMT");
TimeZone TIMEZONE_LOCAL = TimeZone.getDefault(); // GMT + 1
private Calendar getMidnightGmtCalendarWithLocalTimezone() {
Calendar calendar = Calendar.getInstance(Locale.GERMAN);
calendar.set(2017, Calendar.JANUARY, 1, 0, 0, 0);
calendar.setTimeZone(TIMEZONE_GMT); // Probably not required
assertEquals(0, calendar.get(Calendar.HOUR_OF_DAY)); // Assert 1
// Log.i("TAG", "" + calendar.get(Calendar.HOUR_OF_DAY));
calendar.setTimeZone(TIMEZONE_LOCAL);
assertEquals(1, calendar.get(Calendar.HOUR_OF_DAY)); // Assert 2
return calendar;
}
Now I delete the 1st assert, and I'd expect nothing changes. Reality: the 2nd assert fails now! I've tried to understand the implementation of .get(), and apparently it does also compute some time, so it's not just collecting the value. Still I don't get why my 2nd assert is failing.
The 2nd assert succeeds again when I uncomment the Log line (just to be sure the problem arises from the calendar.get(), and not the assert!)
So first question: why does this happen? Second qeustion: how can I make sure I've got a Calendar instance with the Local timezone when I've set the time on midnight for Timezone GMT? (in other words, how can I correctly convert timezones?)
EDIT: I'm using this on Android, so cannot use Java8. Joda time (as suggested below) is a great alternative, and I'll definately look into that. However, as answer for my question I'd like to know HOW this works with Java7 Calendar, because I'm bound to that code for the moment.