简介
很多时候日期格式输出是这样的
2018-10-09T17:39:07.097
中间有个T,尴尬,是的我们需要去掉这个T
这方法是springboot封装好了的,我们直接使用即可,普通的配置我就不贴了
(一)、日期格式化输出
{
"code": 1,
"msg": "查询成功",
"data": {
"id": 1,
"licensePlate": "1",
"vehicleNumber": "1",
"remark": "1",
"createTime": "2018-12-24T15:14:26",
"vid": 1
}
}
解决方法1: 在实体的时间字段添加注解 @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@TableField("create_time")
private LocalDateTime createTime;
解决方法2:自定义config
package com.blct.common.core.config;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
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;
/**
* @ClassName: LocalDateTimeSerializerConfig
* @Author: wcs
* @Description:
* @Date: Created in 18:16 2018/12/24
* @Package: com.blct.common.core.config
* @project: carcloud
* @Modified By:
*/
@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());
}
}
到此完成:
{
"code": 1,
"msg": "查询成功",
"data": {
"id": 1,
"licensePlate": "1",
"vehicleNumber": "1",
"remark": "1",
"createTime": "2018-12-24 15:14:26",
"vid": 1
}
}
(二)、LocalDateTime日期格式化输入:加上注解 @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
1.对象中属性接受
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@TableField("create_time")
private LocalDateTime createTime;
2.单个参数接受
@GetMapping("/add")
public void add(@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime qq) {
VehicleEntity vehicleEntity = vehicleService.getById(1);
vehicleEntity.setCreateTime(qq);
System.out.println(qq);
}