Setting Default TimeZone in Spring Boot Application

Introduction
Sometimes, we want to be able to specify the TimeZone used by an application. For a service running globally, this could mean that all servers are posting events using the same TimeZone, no matter their location.
How it Works
The default value for TimeZone is typically based on the operating system of the machine where the JVM is running. We can change this:
- By passing JVM arguments, using the user.timezone argument, in different ways depending on weather we run a task or a JAR
- Programmatically, using the bean lifecycle configuration options (during/before creation of beans) or even inside a class, during execution
Approaches
Setting TimeZone on bootRun Task
If we use the bootRun task to run the application, we can pass the default TimeZone using JVM arguments in the command line. In this case, the value we set is available from the very beginning of the execution:
mvn spring-boot:run -Dspring-boot.run.jvmArguments="-Duser.timezone=Australia/Sydney"
Setting TimeZone on JAR Execution
Similar to running the bootRun task, we can pass the default TimeZone value in the command line when executing the JAR file. The value we set is available from the very beginning of the execution:
java -Duser.timezone=Australia/Sydney -jar my-spring-app-0.0.1-SNAPSHOT.jar
Setting Default TimeZone on Spring Boot Startup
Main Method
package com.cloudtuned;
@SpringBootApplication
public class MainApplication {
public static void main(String[] args) {
TimeZone.setDefault(TimeZone.getTimeZone("GMT+08:00"));
SpringApplication.run(MainApplication.class, args);
}
}
BeanFactoryPostProcessor
package com.cloudtuned;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.TimeZone;
@Component
public class TimeZoneConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(TimeZoneConfig.class);
@PostConstruct
public void init() {
// Set the JVM default timezone
TimeZone.setDefault(TimeZone.getTimeZone("Europe/Stockholm"));
LOGGER.info(String.format("Timezone set to %s", TimeZone.getDefault().getID()));
}
}
Conclusion
In this article, we learned a number of ways of setting the default TimeZone in a Spring Boot Application.




