Java added date to database, time inconsistent

Mysql > select * from ‘date’; mysql > select * from ‘date’; mysql > select * from ‘date’;

Solution 1: Set the time zone for database connection

Add the suffix serverTimezone=Asia/Shanghai to spring.datasource. Url in the springBoot configuration file. Set the local time zone.

Solution 2: Set the mysql time zone

Mysql > query mysql time zone

show variables like "%time_zone%";
Copy the code

This is divided into modifying the current session and global session

  • Modifying the current session takes effect only for the current session. Exiting the session takes effect
  • Modifying a global session takes effect only after exiting the current session

Modify the current session:

SET time_zone = "+8:00";
Copy the code

Modify global session:

SET global time_zone = "+8:00";
Copy the code

It is best to modify the global session here.

The date obtained by Java is inconsistent with the front-end display

The backend time differs from the database time by 8 hours

why

The @RestController annotation interface in SpringBoot returns data in JSON format. Data of date type is converted by the default Jackson framework of Springboot. The Default time zone for the Jackson framework is GMT (8 hours less than China).

The solution

Add configuration to application.yml:

spring:
  jackson:
    time-zone: GMT+8
Copy the code

If you find this article helpful, please give it a thumbs up!