Partner – Microsoft – NPI (cat= Spring Boot)
announcement - icon

Azure Spring Apps is a fully managed service from Microsoft (built in collaboration with VMware), focused on building and deploying Spring Boot applications on Azure Cloud without worrying about Kubernetes.

And, the Enterprise plan comes with some interesting features, such as commercial Spring runtime support, a 99.95% SLA and some deep discounts (up to 47%) when you are ready for production.

>> Learn more and deploy your first Spring Boot app to Azure.

You can also ask questions and leave feedback on the Azure Spring Apps GitHub page.

1. Overview

Sometimes, when we’re storing dates in MySQL, we realize that the date from the database is different from our system or JVM.

Other times, we just need to run our app with another timezone.

In this tutorial, we’re going to see different ways to change the timezone of MySQL using Spring Boot configuration.

2. Timezone as a URL Param

One way we can specify the timezone is in the connection URL string as a parameter.

In order to select our timezone, we have to add the connectionTimeZone property to specify the timezone:

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test?connectionTimeZone=UTC
    username: root
    password:

Also, we can, of course, configure the datasource with Java configuration instead.

We can find more information about this property and others in the MySQL official documentation.

3. Spring Boot Property

Or, instead of indicating the timezone via the connectionTimeZone URL parameter, we can specify the time_zone property in our Spring Boot configuration:

spring.jpa.properties.hibernate.jdbc.time_zone=UTC

Or with YAML:

spring:
  jpa:
    properties:
      hibernate:
        jdbc:
          time_zone: UTC

4. JVM Default Timezone

And of course, we can update the default timezone that Java has.

In order to select our timezone, we have to add the property forceConnectionTimeZoneToSession=true in the URL. And then we just need to add a simple method:

@PostConstruct
void started() {
  TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
}

But, this solution could generate other problems since it’s application-wide. Perhaps other parts of the applications need another timezone. For example, we may need to connect to different databases and they, for some reason, need dates to be stored in different timezones.

5. Conclusion

In this tutorial, we saw a few different ways to configure the MySQL JDBC timezone in Spring. We did it with a URL param, with a property, and by changing the JVM default timezone.

As always, the full set of examples is over on GitHub.

Course – LSD (cat=Persistence)

Get started with Spring Data JPA through the reference Learn Spring Data JPA course:

>> CHECK OUT THE COURSE
res – Persistence (eBook) (cat=Persistence)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.