Tuesday, January 23, 2018

Setting the timezone for your Spring Boot app

Purpose of this blog post

Today all non-trivial web applications and web services get deployed in the cloud. One cannot be very sure in which time zone the app is deployed. But sometimes, the app needs to record everything like log statements, database CRUD operations, etc using a specific time zone. Usually using the UTC time zone works best for such applications.

Setting the time zone 

This short blog post is a way to show how this can be achieved in a java application, specifically a Spring or Spring Boot application.

There are many ways to do it like passing arguments to the JVM at start time which sets the time zone.

Example


java -Duser.timezone=PST ... <app-main-class>

But this is not the best solution as your app might not be the only application running on the JVM. There might be other apps running there too.


Setting time zone easily in Spring Boot

Add the following snippet to your Spring Boot application, typically in the main application class to set the desired time zone. The snippet shows the UTC time zone.

Example


import java.util.TimeZone;
import javax.annotation.PostConstruct;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

public class MyApplication {

    public static void main(String[] args) {
        SpringApplication.run(Ver3Application.class, args);
    }
    
    @PostConstruct
    void setUTCTimeZone(){
        TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
    }
}

Happy coding :)

2 comments:

Unknown said...

Thank you. Very useful.

Duy said...

I want UTC+7 and how to do that