I have a LocalDate
field of an entiry class as below.
@DateTimeFormat (pattern="dd-MM-YYYY")
private LocalDate myDate;
I have a Date
object when printed displays Thu Jul 07 00:00:00 IST 2022
and converted into LocatDate
as below.
LocalDate myLocalDate = LocalDate.ofInstant(myDateObj.toInstant(), ZoneId.of("Asia/Kolkata"));
which gets stored in DB as 2022-07-07
While displying this field on the page it is shown as 07-07-2022 as expected. But from webpage when I try to edit and save it with same format as 07-07-2022, I get the validation error as below.
Failed to convert property value of type 'java.lang.String' to required type 'java.time.LocalDate' for property 'myDate'; Failed to convert from type [java.lang.String] to type [@org.springframework.format.annotation.DateTimeFormat java.time.LocalDate] for value [07-07-2022]
Ensure the pattern in @DateTimeFormat is "dd-MM-yyyy" instead of "dd-MM-YYYY".
The error you're encountering is likely due to a mismatch between the date format specified in your @DateTimeFormat annotation and the default date format used by Spring when parsing the date from the form submission. Update the Annotation like this:
@DateTimeFormat(pattern="dd-MM-yyyy")
private LocalDate myDate;
Regarding database Storage Format:
When you save a LocalDate to a database, it is stored in the database's default date format, which is often YYYY-MM-DD for SQL databases. The formatting specified by @DateTimeFormat does not influence how dates are stored in the database; it only affects how dates are parsed from strings or formatted into strings during data binding.
Reference:
Refer to the DateTimeFormat Documentation for more information on spring's DateTimeFormat annotation. DateTimeFormat follows the original SimpleDateFormat style for date patterns.