javajsonserializationfasterxml

Why YYYY-MM-dd pattern of @JsonFormat serializes 2023-12-31 23:59:59.907 to 2024-12-31 instead of 2023-12-31 with fasterxml?


There is a field in DB with date value

2023-12-31 23:59:59.907

and we serialize it to JSON with

/**
     * Tariff end
     */
    @JsonFormat(pattern = "YYYY-MM-dd")
    @ApiModelProperty(notes = "tariff end date")
    private Date endDate;

Why it is serialized to 2024-12-31 instead of 2023-12-31 with fasterxml? How to work this error around?


Solution

  • The issue with the serialization of the date field could be due to the use of the wrong format pattern in the @JsonFormat annotation. Instead of "YYYY-MM-dd", which represents the year using a week-based year, you should use "yyyy-MM-dd", which represents the year using the calendar year.

    To fix the error, change the pattern in the @JsonFormat annotation to "yyyy-MM-dd" as follows:

    @JsonFormat(pattern = "yyyy-MM-dd")
    @ApiModelProperty(notes = "tariff end date")
    private Date endDate;