使用ajax请求@ResponseBody返回的数据,由于返回的对象中有在数据库中查询的Date类型。在前端页面得到的时间可能为[2023,5,20,18,32,24]数组对象,可以通过以下两种方法进行日期转换,使日期显示为所需要的格式,如(2023-5-20 18:35:24)
方式一:在实体类属性上添加注解@JsonFormat,设置它的patten参数可指定日期的格式,并自动变成String类型
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private LocalDateTime createTime;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private LocalDateTime updateTime;
缺点:只能处理单个属性,需要手动对多个属性添加,需要添加GMT+8,因为和UTC相差8个小时,所以需要+8
方式二:消息转换器,将所有的日期类型,通过序列化转换为指定格式
1.新建配置类并继承WebMvcConfigurationSupport
2.然后重写父类的extendMessageConverters方法
3.创建JSON转换器对象,
4.并指定对象转换器,使用工具包将java对象序列化为json数据,提供在文章末尾
5.把创建的消息转换器加到容器内,此时容器内默认有八个消息转换器,创建时需要将索引提前,可以优先使用
@Configuration
public class MvcConfiguration extends WebMvcConfigurationSupport {
/**
* Spring MVC -> 消息转换器
* 重写父类的extendMessageConverters方法
*/
protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
//需要为消息转换器设置一个对象转换器,对象转换器可以将Java对象序列化为json数据
converter.setObjectMapper(new JacksonObjectMapper());
//将自己的消息转化器加入容器中
converters.add(0,converter);
}
}
public class JacksonObjectMapper extends ObjectMapper {
public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
//public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm";
public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";
public JacksonObjectMapper() {
super();
//收到未知属性时不报异常
this.configure(FAIL_ON_UNKNOWN_PROPERTIES, false);
//反序列化时,属性不存在的兼容处理
this.getDeserializationConfig().withoutFeatures(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
SimpleModule simpleModule = new SimpleModule()
.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)))
.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)))
.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)))
.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)))
.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)))
.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
//注册功能模块 例如,可以添加自定义序列化器和反序列化器
this.registerModule(simpleModule);
}
}
可根据需要选择是否需要秒数进行注释