前端传给我们的是String格式的,通过@DateTimeFormat(pattern = “yyyy-MM-dd”)注解,我们可以直接将数据转换成Date格式,与数据库的日期类型相对应
后端传给前端,称为出参:通过@JsonFormat(pattern = “yyyy-MM-dd”, timezone = “GMT+8”)注解,我们可以转换成我们想要的格式给前端展示
注意事项:
debug的时候,查看里面的时间还是都有T的,只有最后返回给前端的时候没有T
1.Date要设置时区
2.debug看到的时间还是国外的,但是用postman调用是会便格式的
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createDate;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private LocalDateTime createDate;
但是上面方法太麻烦了,不是全局的配置,全局解决T的问题用下面你的方法
创建一个配置类
package com.example.demo.config;
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;
/**
* 关于Java8中localDateTime去掉中间的T
*
* @author lc
* @version 1.0
* @date 2021/11/11 16:48
*/
@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());
}
}
解决localdatetime转换成字符串带有T的问题
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter dfDate = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
user.setUpdateTime(dfDate.format(now));