Spring Boot

How to set Spring Boot SetTimeZone

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 :)

Found a mistake or something out of date? Tell us →

Written by

chandrashekhar

Founder of onlinetutorialspoint.com. Enterprise architect with 15+ years in healthcare technology, designing and running systems on AWS and Azure. Writes about building real things with AI, local AI hardware and cloud certifications.

Keep reading

Ask a question or leave a comment