(本篇博客已於2019-08-28優化更新)web
原因:jdk7的日期類是java.util.date,java.util.Calendar是非線程安全,因此jdk8提供了一個java.time包,用LocalDateTime、LocalDate代替Date,所以不分公司會用到jdk8新功能,天然就會有人再也不使用Date,而是LocalDateTime。spring
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency>
@Configuration public class LocalDateConfig { @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()); } }
@Data public class Student { private LocalDateTime schoolTime; }
@RestController public class TestController { @GetMapping(value ="/test1") public Student test1(){ LocalDateTime date = LocalDateTime.now(); Student student = new Student(); student.setSchoolTime(LocalDateTime.now()); return student; } }
測試接口:localhost:8080/test1安全
{"schoolTime":"2018-10-08 17:29:57"}
上面是一種全局變量設置,若是咱們只是局部變量的格式化的話,那麼把配置類刪除,而後在Student的那個字段加一個註解就能夠了,以下:app
@Data public class Student { @JsonFormat(pattern = "yyyy-MM-dd HH") private LocalDateTime schoolTime; }
咱們並無刪除配置類,可是結果的格式是按照實體類中註解走的,由於實體類的是局部變量,局部變量的優先級高於全局變量!spring-boot
時隔一年從新更新優化博客,感概萬千,嘻嘻。測試