一、在application中配置
spring.mvc.date-format=yyyy-MM-dd HH:mm:ss #对mvc的输出格式进行约束
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss #对全局的日期格式进行约束 但LocalDateTime日期和时间中间会有T
spring.jackson.time-zone=GMT+8 #指定jackson的时区 我们是东八,否则数据库时间会比实际时间晚八小时
spring.jackson.serialization.write-dates-as-timestamps=false #接收时间戳格式 true的话就只能接收时间戳格式
二、添加配置文件,删除LocalDateTime格式中间的T
package com.qnyou.web.config;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@Configuration
public class CustomsDateConvert implements Jackson2ObjectMapperBuilderCustomizer {
@Override
public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
String dateFormat = "yyyy-MM-dd HH:mm:ss";
// 针对于Date类型,文本格式化
jacksonObjectMapperBuilder.simpleDateFormat(dateFormat);
// 针对于JDK新时间类。序列化时带有T的问题,自定义格式化字符串
JavaTimeModule javaTimeModule = new JavaTimeModule();
//序列化 约束返回格式
javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(dateFormat)));
//反序列化 约束接收格式
// javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(dateFormat)));
jacksonObjectMapperBuilder.modules(javaTimeModule);
}
}
三、补充
以上方式都是对全局的日期类型进行格式化,我们可使用注解对对象中的某些日期属性进行格式化
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") //对前端传入的对象类型的时间数据进行格式化
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss") //对json类型的时间数据进行格式化 包括前端传入的和我们传给前端的
private Date createTime;
但这种方式也解决不了LocalDateTime格式化后中间有T