Why does the following method with Calendar APIs in Java work?

Viewed 29

I have the following method that has been for a very long time in a legacy codebase.

public static Calendar nowAsCalendar(String timeZone){
   Calendar FDRCal = GregorianCalendar.getInstance(timeZone);
   FDRCal.setTime(now());
   Calendar cal = Calendar.getInstance();
   cal.set(1, FDRCal.get(1));
   cal.set(2, FDRCal.get(2));
   cal.set(5, FDRCal.get(5));
   cal.set(11, FDRCal.get(11));
   cal.set(12, FDRCal.get(12));
   cal.set(13, FDRCal.get(13));
   cal.set(14, FDRCal.get(14));
}

We are setting a brand new Calendar instance cal that uses the default timezone so I think it should break as we are not setting the timezone in the new Calendar instance. Am I overlooking something?. What is the best way to set the current date with a timezone?

1 Answers

In Calendar.getInstance() the new instance uses your system's default time zone, so failing to set it the time zone won't cause anything to break, unless you require the time zone to be something other than the default.

However, Calendar is an obsolete class with many flaws, and it's really best not to use it any more. The more modern class to represent a date and time with a timezone is java.time.ZonedDateTime.

You can instantiate one of these, using the default time zone and the current date and time, by writing ZonedDateTime.now(). There's also a version where you can pass in a ZoneId for a time zone, if you want a different time zone from the default - that is, you can write something like

ZoneId sydneyTime = ZoneId.of("Australia/Sydney");
ZonedDateTime rightNow = ZonedDateTime.now(sydneyTime);
Related