I too faced similar issue. I guess all the answers added for this question are specific to above question, my solution will explain the issue and provide generic solution.
You may face this issue, when you are using 2 different time-zones for same Date
.
When you do new Date()
, it uses your default time-zone unless you explicitly specify time-zone. Lemme explain this to you with a code-snippet, (you are in India and current date is (9/5/2021, 12 a.m. IST)
// 09/05/2021 00:00:00 IST
Date birthDate = new Date();
Now, when set above birthDate
to model and when it's serialized using JsonFormat. By default JsonFormat uses UTC time-zone.
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy")
private Date birthDate;
Serialization will result in 08/05/2021
, not 09/05/2021
.
Lemme write the dates with timezone that's 08/05/2021 UTC
, and 09/05/2021 IST
.
Lemme add time too for dates, 08/05/2021 18:30:00 UTC
, and 09/05/2021 00:00:00 IST
.
Now you get why its happening, if you see dates are correct, but having different time-zones. There are 2 ways to handle this problem,
- Use same time-zones
- Add time and time-zones too while serializing dates. Like
08/05/2021 18:30:00 UTC
, and 09/05/2021 00:00:00 IST