import com.fasterxml.jackson.databind.deser.std.DateDeserializers;
import com.fasterxml.jackson.databind.ser.std.DateSerializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.TimeZone;
/**
* 文件名: DateSerializerConfig.java
* 作者: xxx
* 时间: 2020/6/30 9:41
* 描述: 统一格式化时间格式
*/
@Configuration
public class DateSerializerConfig {
/**
* 默认日期时间格式
*/
public static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
/**
* 默认日期格式
*/
public static final String DATE_FORMAT = "yyyy-MM-dd";
/**
* 默认时间格式
*/
public static final String TIME_FORMAT = "HH:mm:ss";
/**
* 方法名: jsonCustomizer
* 作者/时间: xxx-2020/5/20
* 描述: 统一配置时间的序列化和反序列化格式
* 参数:
* 返回: org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer
* 异常场景:
*/
@Bean
public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
return builder -> builder
// 设置时区
.timeZone(TimeZone.getTimeZone("Asia/Shanghai"))
// java8 时间序列化和反序列化
.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DATE_TIME_FORMAT)))
.serializerByType(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DATE_FORMAT)))
.serializerByType(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(TIME_FORMAT)))
.deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DATE_TIME_FORMAT)))
.deserializerByType(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DATE_FORMAT)))
.deserializerByType(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(TIME_FORMAT)))
// java8 之前时间序列化和反序列化
.serializerByType(Date.class, new DateSerializer(false, new SimpleDateFormat(DATE_TIME_FORMAT)))
.deserializerByType(Date.class, new DateDeserializers.DateDeserializer(
DateDeserializers.DateDeserializer.instance,
new SimpleDateFormat(DATE_TIME_FORMAT), DATE_TIME_FORMAT));
}
}
Spring boot java8 时间格式化
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...