Date 类型
前端传给后端
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
private Date updateTime;
后端传给前端
- application.yml配置
spring:
...
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
...
- 字段加上注解
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
private Date updateTime;
LocalDateTime类型
前端传给后端
GET请求
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
private LocalDateTime updateTime;
POST请求
字段加上注解 (com.fasterxml.jackson.databind.annotation.JsonDeserialize )
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd HH:mm:ss")
private LocalDateTime updateTime;
或者
@JsonDeserialize(using = DateTimeDeserializer.class)
private LocalDateTime updateTime;
配置类
/**
* 参数配置
* @author guojianfeng
* @date 2019/10/16
*/
public class DateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
@Override
public LocalDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
if (StringUtils.isBlank(jsonParser.getText())){
return null;
}
LocalDateTime localDateTime = LocalDateTime.parse(jsonParser.getText(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
return localDateTime;
}
}
后端传给前端
添加依赖
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.8.9</version>
</dependency>
添加配置 ``` package com.clamc.valuationdisclosure.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;
/**
- 描述:日期统一处理 *
@author guojianfeng at 2019/9/15 16:09 */ @Configuration public class WebDateConfig { @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());
} }
2. 当然因为后端传给前端是用的RestController,也就是序列化的方式,也是可以采用前端传给后端POST的请求的方式。
<a name="1PFCm"></a>
### 和数据库匹配
1. 添加依赖
```xml
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-typehandlers-jsr310</artifactId>
<version>1.0.1</version>
</dependency>