很多时候日期格式输出是这样的
2018-10-09T17:39:07.097
中间有个T,尴尬,是的我们需要去掉这个T
这方法是springboot封装好了的,我们直接使用即可,普通的配置我就不贴了
教程
一、全局配置模式
创建日期config类
@Configuration
public class LocalDateTimeSerializerConfig {
@org.springframework.beans.factory.annotation.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());
}
}
实体类,get,set忽略
public class TestEntity {
private String name;
private LocalDateTime dateTimes;
}
controller使用
@GetMapping("/test")
public TestEntity test(){
TestEntity testEntity=new TestEntity();
testEntity.setName("admin");
testEntity.setDateTimes(LocalDateTime.now());
return testEntity;
}
成功效果
{"name":"admin","dateTimes":"2018-10-09 17:39:07"}
二,最为现在常用的方式
@JsonFormat注解
public class OrderInfo {
@JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime createTime;
@JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
private Date updateTime;
public LocalDateTime getCreateTime() {
return createTime;
}
public void setCreateTime(LocalDateTime createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
}
来源:oschina
链接:https://my.oschina.net/lenglingx/blog/4276372