In this tutorial, I am going to show how to set/change the time zone in spring boot application.
Spring Boot SetTimeZone :
JVM will take the default time zone as the server’s time zone. For example, if the server is running on IST, then the JVM takes the IST time as default.
In Spring boot we can quickly change/set this default timezone using java.util.TimeZone class like below.
Application.java
package com.onlinetutorialspoint.SpringBoot_Custom_ErrorPage;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.TimeZone;
@SpringBootApplication
public class Application {
@PostConstruct
public void init(){
// Setting Spring Boot SetTimeZone
TimeZone.setDefault(TimeZone.getTimeZone("IST"));
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Run Application :
[INFO] --- spring-boot-maven-plugin:1.5.10.RELEASE:run (default-cli) @ SpringBoot_Custom_ErrorPage ---
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.5.10.RELEASE)
2018-02-17 20:43:21.353 INFO 10356 --- [ main] c.o.S.Application : Starting Application on DESKTOP-RN4SMHT with PID 10356 (E:\work\SpringBoot_Custom
_ErrorPage\target\classes started by Lenovo in E:\work\SpringBoot_Custom_ErrorPage)
2018-02-17 20:43:21.353 INFO 10356 --- [ main] c.o.S.Application : No active profile set, falling back to default profiles: default
2018-02-17 20:43:21.462 INFO 10356 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebA
pplicationContext@62f32a29: startup date [Sat Feb 17 20:43:21 IST 2018]; root of context hierarchy
2018-02-17 20:43:24.572 INFO 10356 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
You can see the updated time zone while running the application above.
Happy Learning 🙂