Guide to time zone handling for REST APIs in Java
The Greenwich Meridian line

Guide to time zone handling for REST APIs in Java

No alt text provided for this image


This is the first part of two parts series of articles. I am trying to cover up the mostly theoretical (without code example) parts under this article and in the next one willing describe with a  practical example with front end client using Angular, back end server Spring boot using MySQL Server DB.

Before start, if someone is already confused with the terms being using when talking about Time Zone, like GMT(Greenwich Mean Time), UTC (Coordinated Universal Time), DST (Daylight Saving Time)  may refer to this and get an idea of what is all this about GMT vs UTC vs DST

It is true that handling timezone could be tricky sometimes, not only for the APIs but also for mobile apps and distributed web applications. Especially with the modem day cloud base architectures, it is not unusual that different layers of your application could run on different time zones. Also, there are many countries like the USA, Canada, Australia, Indonesia which extended to more than time zones.

For Example, Let's think you are developing a taxi booking app and your app is going to operate in a country like the USA where it has spread in multiple time zones. What will happen if a user book a taxi at 2.30 pm and the cab is already located in another region where it's 1 hour ahead of users located. I donk think your app will work out for so long.

Time Zones in 2012

Time Zones in 2012

So it's obvious that we need a mechanism to handle this time gap. If you don’t think about that at the time of designing the application, mostly you will end up in a tragedy with supporting different time zone not just because there might be users in different time regions but also due to the factors like volatile time due to daylight savings (DST).

let's learn the standard first. What is the international standard?

There are two international representations for date and time.

  1. ISO_8601 which is string (text) representation for dates Ex. 2021-06-3T17:55:02+0000

No alt text provided for this image

Here what offset exactly means is that the time is 5 hours and 30 minutes higher than UTC. In otherward, you need to reduce that offset to get the UTC.

2. Epoch time is the number representation for dates. Ex 1623606902 This is the calculation of the seconds that has been spent from 1 January 1970. It depends that where you should use ISO and where you should use epoch, it says epoch is more suitable for IoT applications while ISO is preferable for other day-to-day applications because of human readability and so on. 

Introduction to java time API

There were several well-known java class that has been used for Data time handing in java, like java.util.Date, java.util.Calander prior to the introduction of the java.time api in version 8. One of the main reasons behind the introduction of java.time API is that the incapability of proper time zone handing in old Date and Calendar classes. From Java 8 onwards it's highly recommended to use java.time api classes over old legacy classes.

No alt text provided for this image

Rest API time zone handling with different architectures.

There are quite a several important factors that you should thoroughly consider dealing with the time zones. Let’s consider an application architecture as showing below image. Terms IST - India standard time and BST - British Summer Time will be used in the next sections of the article.

No alt text provided for this image

In the above architecture both the application server and database server running in the same Time Zone. In this case, there is no need for additional effort to handle the time zone mechanism inside the application.

Because what application is being used is always compatible with what persists on DB. This approach is probably fine if you don’t have to cater to time zone changes/ daylight saving time changes. But this is verbose when your DB has to expose to another third-party system which is been used in the different time zone

No alt text provided for this image

As a standard, it's recommended to keep the database in the UTC zone. Which makes it more flexible and supportive to deal with applications which running in different time zones. And also another benefit of dealing with DST (Daylight Saving Time) is that you don’t need to adjust accordingly. 

 But keeping the database time zone in UTC doesn’t make any sense if your dates are not stored in the UTC. So all the applications which dealing with the database need to guarantee that it always stores their date/times in UTC. which means it will bring you the pain of doing time zone adjustment for each query run over the DB.

 But with the modern-day frameworks like hibernate/Spring data could relieve your pain by handling the time zone adjustment for you. You just need to specify bellow configuration in your application

#for plain hibernate
hibernate.jdbc.time_zone=UTC

#for Spring boot jpa
spring.jpa.properties.hibernate.jdbc.time_zone=UTC        

In other frameworks like Spring JDBC (JDBC Templates) you will have to handle the time gap manually. Otherwise, the times in your DB are not stored exactly in UTC even it is supposed to be.

*Extra: If you are running databases on UTC (Docker default to UTC) is always possible for you to change the time zone with TZ environment variable, by default Docker container, configure to UTC. For other use cases if the DBs are running on a server machine it will take the local machine default time zone, but with most modern RDBMS you will be able to change time zone easily.

API Dos and Don’ts 

There are a few important factors that you should thoroughly consider dealing with the time zone.

 1. Never store the date as varchar (datatype Text in the database).

Storing the dates in varchar/text format is always a bad practice. Because you will miss most of the supports given by the DB for managing time and time zones.

  • Very first thing is that you have to handle the data/time transformation manually and that is a hassle and error-prone.
  • The next one is you will be missed the framework/ DB connector driver support to handle the date-time, again the time zone as well.
  •  The most important loss is that you will not get the automatic daylight saving. That is crucial because almost all the modern-day RDBMS are supporting automatic daylight saving and it is not easy to handle by yourself. 

The daylight saving time is not something happening on a specific day and also the mechanism is different from region to region.  Check the chart given bellow

No alt text provided for this image

  • The last point is that the database features like ordering/sorting will not bring the desired result depending on the format you store it.

 2. Always try to keep the date-time as TIMESTAMP/ DATETIME in the database.

 As mentioned in the first point it will provide the natural time zone and daylight saving time adjustment freeing your mind manually dealing with those.

 But deciding which datatype will match best for you may be tricky if you exactly don’t know how those data types behave. 

 Each Database like Oracle, MsSqL, Mysql has its supports and restrictions when it’s come to the datatype.

 As an example for MySQL Databases, it has a particular date range it supports for Timestamp ( 1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC) means the database will throw an error if you try to store a date beyond the range.

 for DATETIME it has range from '1000-01-01 00:00:00' to '9999-12-31 23:59:59'

 Also, the databases have their own format when it’s come to literate the date-time.

 again for MySql if you use '2020-01-01 10:10:10+05:30' this will automatically adjust the time according to the DB time zone before storing for most latest connector drivers.

 3. Always keep the database in UTC unless there is a very specific reason.

 The most preliminary reason to use UTC is that it’s the standard. Following standard always make it easy to deal with any other application, data export/ data loads.

 As mentioned earlier UTC is always reliable and it doesn’t shake for DST changes. All other time zones can change them not only offset but also name with political reasons.

 syntactically also less verbose with ending ‘Z’ character, not like other ‘+05.30’ format.

 4. Don’t try to handle the time zone manually when dealing with frameworks.

 Don't need to burn your hand when the plier is around, which means let the framework deal with time zone adjustments. Most of the modern-day frameworks like hibernate/spring data itself support on-the-fly time zone adjustments/ daylight saving adjustments so on. It is much secure and will reduce your much work handling it manually.

 but there may be a particular reason someone to use old JDBC or any other legacy way of dealing with a database, even in that case also try to use a more sophisticated connector to deal with. 

 5. Always Avoid legacy classes like java.util.Date & Calendar

 The main reason java come up with the latest more sophisticated time API is due to the lack of support of old legacy data structure.

 But java hasn’t still removed the support for those classes due to backward compatibility even though most of the classes have been deprecated.

 With the JDBC 4.2 version onwards its supporting java time API classes.

 So except for an unavoidable reason like developers should always encourage to use modern java classes when dealing with Date time.

For Example, the Latest Postgres JDBC drivers don’t support both java.util.Data. 

 Conclusion.

 It is obvious that the restful APIs are supposed to deal with any 3rd parties who need to interact with a server, which always uses text or JSON representation. in that case, the server is not aware of that from which time zone the request came from otherwise we specify it a different parameter. For example, we may expose the API with a separate time zone parameter that and the user may call the server endpoint with his local date-time. But that is one bad approach.

 It is far easy to deal with international standard as the data representation always carry the time zone offset with it. So there is no need for the client to send time zone variable separately with each request or transform its data time values according to what rest API is looking for.

 As per The 5 laws of API given here we API should always accept any time zone and return UTC.

 On the java server-side there are several ways that you can read the API parameters and convert them to java specific objects. Easiest Is to let the Jackson framework handle it. Latest Jackson API came up with the java time API support so you may convert the text representation send by the API client to any java class type.

 But it is recommended to use OffsetDateTime since the capability of easy handling time zone and you can transform to Local Dates and Time easily. And it also guarantees that you are exactly storing dates in DB in UTC.

Again in the use cases like both your application and the database server running in the same time zone still could use LocalDateTime without any additional coding. and if the application and DB running at two different time zones still you can use LocalDateTime but in that case, the Application should be aware that what time zone DB running and need to transform each time wrings the date-time to the DB time zone and also when reading back.

 The reason to suggest OffSetDateTime over ZonedDateTime is the wide range of database driver support. Almost all the latest JDBC drivers supporting OffsetDateTime. For Example, the Latest Postgres JDBC drivers don’t support ZonedDateTime 

 In the next article, I am thinking of providing practical examples steps by steps to demonstrate.

Special Remaks

 http://apiux.com/2013/03/20/5-laws-api-dates-and-times/

 https://dev.mysql.com/doc/refman/8.0/en/datetime.html

 https://www.baeldung.com/jpa-java-time

 https://www.baeldung.com/migrating-to-java-8-date-time-api

 https://stackoverflow.com/questions/32437550/whats-the-difference-between-instant-and-localdatetime/32443004#32443004

To view or add a comment, sign in

More articles by Anushka Darshana

Others also viewed

Explore content categories