On a Linux server in the Czech Republic there are several Spring Boot applications. One of them is used by a customer in Mexico. The server and PostgreSQL running on it are both configured for default UTC timezone.
The goal is to set the application's time zone to Mexico, so the customer will see correct dates and times.
Time zone for Java application
The best way to override system's time zone is to use non invasive VM option -Duser.timezone=America/Monterrey
.
Worse solution, but quite popular on the stack overflow is to override it programmatically by calling TimeZone.setDefault(TimeZone.getTimeZone("America/Monterrey"));
somewhere in the application's main method.
Time zone for database session
Every database connection should be initialised with a statement that sets time zone run-time parameter to Mexico.
Fortunately, Spring Boot 2 reintroduced init-sql configuration properties for its datasources so this is an easy task to do.
For a default Hikari datasource write into your application.properties file:
spring.datasource.hikari.connection-init-sql=SET TIME ZONE 'America/Monterrey'
If you are using non-default Tomcat datasource, write:
spring.datasource.tomcat.init-s-q-l=SET TIME ZONE 'America/Monterrey'
There is also possibility to set the default run-time parameter for all connections to a specific database by executing following statement.
ALTER DATABASE postgres SET timezone TO 'America/Monterrey';
SELECT pg_reload_conf();
I don't recommend this solution because it can confuse clients and applications connecting to the database from other parts of the world.