springcloud-community / springcloud-comment

0 stars 0 forks source link

post/2022-09/springboot-date-format/ #3

Open utterances-bot opened 1 year ago

utterances-bot commented 1 year ago

Formatting json Date/LocalDateTime/LocalDate in Spring Boot - Spring Cloud

Learn how to format json Date, LocalDateTime, LocalDate objects in Spring Boot.

https://www.springcloud.io/post/2022-09/springboot-date-format/

KevinBlandy commented 1 year ago

How to configure the formatting of ZonedDateTime ? You can refer to the following code.

@Bean
public Jackson2ObjectMapperBuilderCustomizer zonedDateTimeCustomizer() {

    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    return builder -> {
        builder.serializers(new StdSerializer<>(ZonedDateTime.class) {
            private static final long serialVersionUID = 7267001379918924374L;
            @Override
            public void serialize(ZonedDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
                gen.writeString(value.format(dateTimeFormatter));
            }
        });
        builder.deserializers(new StdDeserializer<>(ZonedDateTime.class) {
            private static final long serialVersionUID = 154543596456722486L;
            @Override
            public ZonedDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JacksonException {
                return ZonedDateTime.parse(p.getText(), dateTimeFormatter.withZone(ZoneId.systemDefault()));
            }
        });
    };
}

This is a question posed by @Vikita on Twitter.