Java util Date,Calendar & the Timezone Hell!

Sai Pitchuka
2 min readJun 19, 2018

When you are using Java.util package’s classes like Date,Calendar etc ,quite often than not one would need to get the date or Calendar populated with current date,time.

In such cases,we can obtain that using below

Date currentDate = new Date();
Calendar currentCalendar = Calendar.getInstance();

Let’s say we want to print these values.When we print the values to console, the values that will be output to console will be something like this.

System.out.println(currentDate);
System.out.println(currentCalendar);
------------------------------------
Output:
Tue Jun 19 20:02:38 IST 2018
Tue Jun 19 20:02:38 IST 2018

You can see the output value being shown is represented in the underlying timezone the application is running on i.e IST in this case.If the same code is run on another application running with a different timezone let’s say UTC the values will be something like this.

Output when run on appication with UTC timezone:
Tue Jun 19 14:32:38 UTC 2018
Tue Jun 19 14:32:38 UTC 2018

So,the actual values being displayed depends on underlying timezone.This could cause problems when this field is part of a Hibernate model object contained in a module which is shared between two applications and both the applications write to the same database and when the applications are running on different timezones.We would want to populate a field in a database table column with date values in a specific timezone.But,in this case if we are generating the date or calendar objects in the way that we were doing earlier,It would create a problem where one application generates the date in one timezone and the other application in another timezone but the correct way is to store the dates in one consistent timezone.

How can we deal with this problem?One solution is to use the java8’s time package’s classes like ZonedDateTime.But there may be a case when you can’t afford to do this and you have to somehow deal with the Calendar or Date objects.

In such cases,we can use the below ,assuming the consistent timezone that we want to generate the UTC.

Calendar currentCalendar = GregorianCalendar.from(ZonedDateTime.of(LocalDateTime.now(Clock.systemUTC()),ZoneId.systemDefault()));Date currentDate = Date.from(LocalDateTime.now(Clock.systemUTC()).atZone(ZoneId.systemDefault()).toInstant());

If we use the above way to get the current date time values,when you output the values to console, the values will be in only one consistent timezone(UTC in this case).

Please visit my YouTube channel https://youtube.com/channel/UC-8tqCyhtt6Lt5-n2UMZB_A

--

--