Troubleshooting the problem that the data time returned by the SpringBoot interface is 8 hours different from the actual time

scene description

A SpringBoot application was deployed in the container and requested an interface. The time returned by the interface was 8 hours different from the actual time.

Possible Causes

1. The time zone of the container differs from the actual time zone by 8 hours.
2. The jvm time zone differs from the actual time zone by 8 hours.
3. The time after being stored in the database differs by 8 hours
. 4. The time obtained by the backend is the same, but the time difference after returning to the front end is 8 hours.

Troubleshooting steps

1. Enter the container to view the time

$ date

2. Write a java application to view the jvm time

import java.util.Date;

public class Demo {
    
    
   public static void main(String[] args) {
    
    
       Date date = new Date();
       System.out.println(date);
   }
}

3. Check the database time
. Open the database and check whether the database time stored in the database is consistent with the actual time.
4. Print out the time of the data obtained by the backend in the background to see whether it is consistent with the front-end.

solution

The container time zone differs from the actual time zone by 8 hours

If the time obtained in the first step of troubleshooting is 8 hours different from the actual time, it is recommended to add the following content to the Dockerfile of the container:

RUN cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
RUN echo 'Asia/Shanghai' >/etc/timezone

The difference between jvm time zone and actual time zone is 8 hours

If the time obtained in the second step of the troubleshooting differs by 8 hours from the actual time, you can add the following code to the aspect-oriented aspect of SpringBoot or the main class.

@PostConstruct
void started() {
    
    
    TimeZone.setDefault(TimeZone.getTimeZone("GMT+8"));
}

The time stored in the database differs by 8 hours from the actual time zone

If the time obtained in the third step of the troubleshooting differs by 8 hours from the actual time, you can modify the database connection information in the SpringBoot application configuration file application.yml and addserverTimeZone=GMT%2b8

Spring's json constructor causes time zone inconsistency

The root cause of the above three situations is that the initial time zone of the environment is not configured. The best solution is to configure the respective time zones before application deployment.
In the fourth step of troubleshooting, there is an inconsistency in the time zone. The reason is that the time zone of spring's json constructor is inconsistent with the actual time zone. You can modify the springboot configuration file application.yml and add the following content:

spring:
  jackson:
    time-zone: GMT+8
    date-format: yyyy-MM-dd HH:mm:ss

Guess you like

Origin blog.csdn.net/Loiterer_Y/article/details/109381131