由于时间格式可能多种多样,为了防止出现不常见的时间格式,我们进行全局处理:
package com.llpp.config;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
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 org.springframework.core.convert.converter.Converter;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
/**
* @Author 21326
* @Date 2024 2024/9/21 2:36
*/
@Configuration
public class DateConverterConfig {
private static final String DATETIMEFORMAT = "yyyy-MM-dd HH:mm:ss"; // 日期时间格式
private static final String DATEFORMAT = "yyyy-MM-dd"; // 日期格式
// 项目全局的时间出参格式化
@Bean
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
return builder -> {
builder.simpleDateFormat(DATEFORMAT);
builder.simpleDateFormat(DATETIMEFORMAT);
builder.serializers(new LocalDateSerializer(DateTimeFormatter.ofPattern(DATEFORMAT)));
builder.serializers(new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DATETIMEFORMAT)));
};
}
// 自定义时间转换器
@Bean
public Converter<String, LocalDate> localDateConverter() {
return new Converter<String, LocalDate>() {
@Override
public LocalDate convert(String source) {
// 使用指定格式解析字符串为LocalDate
return LocalDate.parse(source, DateTimeFormatter.ofPattern(DATEFORMAT));
}
};
}
// 自定义时间转换器
@Bean
public Converter<String, LocalDateTime> localDateTimeConverter() {
return new Converter<String, LocalDateTime>() {
@Override
public LocalDateTime convert(String source) {
// 使用指定格式解析字符串为LocalDateTime
return LocalDateTime.parse(source, DateTimeFormatter.ofPattern(DATETIMEFORMAT));
}
};
}
}