Jackson @JsonFormat set date with one day less

血红的双手。 提交于 2019-11-29 21:47:02

Hey guys 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

@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.

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.

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;
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!