FasterXML / jackson-annotations

Core annotations (annotations that only depend on jackson-core) for Jackson data processor
https://github.com/FasterXML/jackson
Apache License 2.0
1.03k stars 330 forks source link

JsonFormat timezone bug #176

Closed liuyuqiang closed 4 years ago

liuyuqiang commented 4 years ago

Why @JsonFormat default timezone always UTC not TimeZone.getDefault() ? How to configure it. use system default

cowtowncoder commented 4 years ago

Please ask usage questions on mailing list (https://groups.google.com/g/jackson-user) or chat https://gitter.im/FasterXML/jackson-databind

winne42 commented 4 years ago

for me this sounds like either https://stackoverflow.com/questions/49061391/jackson-jsonformat-deserialize-always-in-utc or https://stackoverflow.com/questions/55224233/jsonformat-default-timezone-doesnt-seem-to-be-working

Could somebody close this non-issue then? @cowtowncoder ?

imgoby commented 1 month ago
  1. DateTimeJsonFormatSerializer

import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import lombok.extern.slf4j.Slf4j;

import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone;

@Slf4j public class DateTimeJsonFormatSerializer extends JsonSerializer { public static final String TIME_FMT="yyyy-MM-dd HH:mm:ss";

public DateTimeJsonFormatSerializer() {
    log.info("DateTimeJsonFormatSerializer default timezone:" + TimeZone.getDefault().getID());
}

@Override
public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
    TimeZone timeZone = TimeZone.getDefault();

// TimeZone timeZone = TimeZone.getTimeZone("Asia/Shanghai");

    SimpleDateFormat dateFormat = new SimpleDateFormat(TIME_FMT);
    dateFormat.setTimeZone(timeZone);
    jsonGenerator.writeString(dateFormat.format(date));
}

}



2 Model

    @JSONField(format = DateTimeJsonFormatSerializer.TIME_FMT)
    @JsonSerialize(using = DateTimeJsonFormatSerializer.class)
    private Date time;