How do I force a Spring Boot JVM into UTC time zone?
I think you can set your application's timezone on your application level. I think this link will help you. https://www.onlinetutorialspoint.com/spring-boot/how-to-set-spring-boot-settimezone.html
So What you need to do is adding "@PostConstruct" annotation to the main class where "@SpringBootApplication" annotation is located, and add timezone setting method there. Here is an example.
@SpringBootApplication
public class HellotimezoneApplication {
public static void main(String[] args) {
SpringApplication.run(HellotimezoneApplication.class, args);
}
@PostConstruct
public void init(){
// Setting Spring Boot SetTimeZone
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
}
}
Hope this can help you!
You can configure the timezone with a class annotated with the @Configuration
annotation. You can put it anywhere in your project. I typically house all classes that fit under this category in a package called config
. Make sure you add the @PostConstruct
annotation to the method that is actually setting the timezone.
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
@Configuration
public class LocaleConfig {
@PostConstruct
public void init() {
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
System.out.println("Date in UTC: " + new Date().toString());
}
}
See the original article
More options in case your application is running under linux:
Set TZ
environment variable
See "In POSIX systems, a user can specify the time zone by means of the TZ environment variable" (https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html).
This option is especially useful in any cloud environment.
Symlink /etc/locatime
I.e. in my local system /etc/locatime
symlinks to /usr/share/zoneinfo/Europe/Berlin
:
➜ ls -l /etc/localtime
lrwxrwxrwx 1 root root 33 22. Jan 23:01 /etc/localtime -> /usr/share/zoneinfo/Europe/Berlin
You can easily change the symbolic link with ln -s /usr/share/zoneinfo/GMT /etc/localtime
, the possible values can be found within /usr/share/zoneinfo/
.
This option can also be used in many cloud environments by mounting a hostvolume, see kubernetes timezone in POD with command and argument.
Use spring-boot.run.jvmArguments
property if you want to pass JVM options from Maven Spring Boot Plugin to forked Spring Boot application:
<properties>
<spring-boot.run.jvmArguments>-Duser.timezone=UTC</spring-boot.run.jvmArguments>
</properties>
This is be equivalent to command line syntax:
mvn spring-boot:run -Dspring-boot.run.jvmArguments="-Duser.timezone=UTC"
or when running a fully packaged Spring Boot application:
java -Duser.timezone=UTC -jar app.jar