Search code examples
javaspringspring-bootdate

Spring Boot Wrong date returned


I have an entity Person

@Entity
@Data
public class Person {

  @Temporal(TemporalType.DATE)
  private Calendar dob;
}

And some dao classes

@Data
public class PersonResponse {

  @JsonFormat(pattern = "yyyy-MM-dd")
  private Calendar dob;
}
@Data
public class PersonRequest{
  @DateTimeFormat(pattern = "yyyy-MM-dd")
  private Calendar dob;
}

When storing values it works perfectly. Example if I send "2000-01-01" it's stored as is in the database "2000-01-01". But When I try to return it I get "1999-12-31".

Now it's clear that is a Timezone Problem but I don't know how to fix it.

My explanation for the cause

The user timezone is GMT+1 so it is some how retrieved as "2000-01-01T00:00:00.000 +01:00", then parsed to UTC "1999-12-31T23:00:00.000 +00:00" to finally be returned as "1999-12-31".

But why? And how can I prevent this knowing that users timezones can change (so adding the time offset manually of 1 hour won't work).

I tried also changing type from Calendar to java.util.Date and java.sql.Date... but no result.

Similar questions where asked before like this one but I still couldn't understand how to fix it


Solution

  • If Applicable try to switch from class Calendar to LocalDate. LocalDate does not take time zone into consideration. This should resolve your issue (and simplify your code). Also, for formatting the LocalDate with Json see the answer to this question: Spring Data JPA - ZonedDateTime format for json serialization