Jackson @JsonFormat set date with one day less

@William's answer works but you should add theses lines to your application.properties files instead:

spring.jackson.time-zone=Brazil/East
spring.jackson.locale=pt-BR

In that way, you indicate the time-zone and locale only one time, and it applicate to all the Date of your application.


Use this solution, it is more effective and modern than my solution: https://stackoverflow.com/a/45456037/4886918

Thanks @Benjamin Lucidarme.

I resolved my problem using:

@Temporal(TemporalType.DATE)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy", locale = "pt-BR", timezone = "Brazil/East")
private Date birthDate;

I changed timezone to "Brazil/East" or "America/Sao_Paulo" and working now

Thanks


I'd go with setting ObjectMapper timezone as default JVM timezone:

    ObjectMapper objectMapper = new ObjectMapper();
    //Set default time zone as JVM timezone due to one day difference between original date and formatted date.
    objectMapper.setTimeZone(TimeZone.getDefault());

It's a better solution if you don't know what timezone is used on a server environment.

In spring-boot environment you can override default JacksonAutoConfiguration:

@Bean
ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
    return builder.createXmlMapper(false)
            // Set timezone for JSON serialization as system timezone
            .timeZone(TimeZone.getDefault())
            .build();
}

On both side (Client - Server) annotate your date filed like this:

@JsonDeserialize(using = JsonDateDeserializer.class)
@JsonSerialize(using = JsonDateSerializer.class)
private Date birthDate;

and on both side again put this implementations for serializing and deserializing:

public class JsonDateSerializer extends JsonSerializer<Date> {
    SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");

    @Override
    public void serialize(final Date date, final JsonGenerator gen, final SerializerProvider provider) throws IOException, JsonProcessingException {

        String dateString = format.format(date);
        gen.writeString(dateString);
    }

}


public class JsonDateDeserializer extends JsonDeserializer<Date> {

    SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");

    @Override
    public Date deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException {
        if (jp.getCurrentToken().equals(JsonToken.VALUE_STRING)) {
            try {
                Date date = format.parse(jp.getText().toString());
                return date;
            } catch (ParseException e) {
                //e.printStackTrace();
            }
        }
        return null;
    }

}