Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Some time ago, I encountered a ridiculous problem, the user’s birthday was directly lost by one day through the return of the back-end. The debug found that the database returned the correct value every time during debugging, but there was something strange in the interface response body, which reduced by one day.

Debugging process:

At the beginning, debug is used to see if the database is a ghost, and find that the data from the database out of everything is normal.

So this is weird, why is there a problem with the response of an interface where the data is true?

Then we tested several sets of data and found that it was even weirder. Some dates were normal, while others were not, especially dates close to the user’s birthday, which had a high probability of losing one day. And then I added more test cases, more data sets and put the error time between 1886 and 1991. And I changed @jsonformat (pattern = “YYYY-MM-DD “, timezone = “GMT + 8″) to @jsonformat (pattern =” YYYY-MM-DD HH: MM :ss”, Timezone = “GMT + 8”) check whether the date is due to the timezone and find that the date is only one hour shorter than normal.

Then I went to Baidu to search the time node less than an hour, and found a concept is daylight saving time.

From 1986 to 1991, except 1986, which was the first year of daylight saving time, from May 4 to September 14, the other years were implemented in accordance with the specified period of time, the time was moved forward by one hour.Copy the code

JsonFormat does not handle daylight saving time. Then I inquired about the relevant solutions.

JsonFormat is derived from the SpringBoot package, and it is uncertain whether the higher version will have relevant optimizations.

Solution:

1. Use VM parameters

-Duser.timezone=GMT+08

Timezone =GMT+08Copy the code

2. Use SimpleDateFormat

SimpleDateFormat Format Date does not have this problem in the test. You can format the Date manually or use string concatenation, depending on the business scenario.