前端传String类型,后端转LocalDateTime的三种⽅法
1. 后端可⽤String接收,再转LocalDateTime
特点:适⽤于此类型参数较少的场景
2. 前端传"2021-05-16 12:10:10"类型,后端借助注解,使⽤LocalDateTime接收
@JsonFormat(pattern ="yyyy-MM-dd HH:mm:ss", timezone ="GMT+8")
private LocalDateTime time;
3. 前端传"2021-05-16 12:10:10"类型,后端借助配置类,使⽤LocalDateTime接收
import JavaTimeModule;
import LocalDateTimeDeserializer;
import LocalDateSerializer;
import LocalDateTimeSerializer;
import Jackson2ObjectMapperBuilderCustomizer;
import Bean;
import Configuration;
import Converter;
import LocalDate;
import LocalDateTime;
import DateTimeFormatter;
@Configuration
public class LocalDateTimeSerializerConfig {
private static final String DATE_TIME_PATTERN ="yyyy-MM-dd HH:mm:ss";
private static final String DATE_PATTERN ="yyyy-MM-dd";
/
**
* string转localdate
*/
@Bean
public Converter<String, LocalDate>localDateConverter(){
return new Converter<String, LocalDate>(){
@Override
public LocalDate convert(String source){
im().length()==0){
return null;
}
try{
return LocalDate.parse(source);
}catch(Exception e){
return LocalDate.parse(source, DateTimeFormatter.ofPattern(DATE_PATTERN));
}
}
};
}string转date的方法
/**
* string转localdatetime
*/
@Bean
public Converter<String, LocalDateTime>localDateTimeConverter(){
return new Converter<String, LocalDateTime>(){
@Override
public LocalDateTime convert(String source){
im().length()==0){
return null;
}
// 先尝试ISO格式: 2019-07-15T16:00:00
try{
try{
return LocalDateTime.parse(source);
}catch(Exception e){
return LocalDateTime.parse(source, DateTimeFormatter.ofPattern(DATE_TIME_PATTERN));
}
}
};
}
/**
* 统⼀配置
*/
@Bean
public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer(){
JavaTimeModule module=new JavaTimeModule();
LocalDateTimeDeserializer localDateTimeDeserializer =new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
module.addDeserializer(LocalDateTime.class, localDateTimeDeserializer);
return builder ->{
builder.simpleDateFormat(DATE_TIME_PATTERN);
builder.serializers(new LocalDateSerializer(DateTimeFormatter.ofPattern(DATE_PATTERN)));
builder.serializers(new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DATE_TIME_PATTERN)));
};
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。