Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JDK8 日期格式化 #12

Open
jerrychir opened this issue Jan 15, 2019 · 0 comments
Open

JDK8 日期格式化 #12

jerrychir opened this issue Jan 15, 2019 · 0 comments

Comments

@jerrychir
Copy link
Owner

JDK8 日期格式化

方案一(全局)

只需要定义一个配置类,在里面定义两个 Bean 即可完成全局日期格式化处理,这种方式同时还兼顾了 Date 和 LocalDateTime 并存

import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Configuration
 public class LocalDateTimeSerializerConfig {

    @Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
    private String pattern;

    @Bean
    public LocalDateTimeSerializer localDateTimeDeserializer() {
        return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern));
    }

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return builder -> builder.serializerByType(LocalDateTime.class, localDateTimeDeserializer());
    }
}

方案二

我们对日期格式要做特殊的处理,全局的格式化方式无法满足我们需求是,使用该方案是非常好的选择,通过 @jsonformat 注解我们可以更为精准的为日期字段格式化,它也是优先级最高的

@JsonFormat(pattern = "yyyy-MM-dd")
private LocalDateTime payTime;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant