javascript
Spring Boot——LocalDateTime格式化配置
?在項(xiàng)目中日期格式化是最常見的問(wèn)題,之前涉及的?java.util.Date 和 java.util.Calendar 類易用性差,不支持時(shí)區(qū),非線程安全,對(duì)日期的計(jì)算方式繁瑣,而且容易出錯(cuò),因?yàn)樵路菔菑?開始的,從 Calendar 中獲取的月份需要加一才能表示當(dāng)前月份。
在 JDK8 中,一個(gè)新的重要特性就是引入了全新的時(shí)間和日期API,它被收錄在 java.time 包中,借助新的時(shí)間和日期API可以以更簡(jiǎn)潔的方法處理時(shí)間和日期。
解決方案
1、注解
(1)?@JsonFormat和@DateTimeFormat
@JsonFormat后臺(tái)到前臺(tái)的時(shí)間格式的轉(zhuǎn)換
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
pattern:需要轉(zhuǎn)換的時(shí)間日期的格式
timezone:是時(shí)間設(shè)置為東八區(qū)
@DateTimeFormat前后到后臺(tái)的時(shí)間格式的轉(zhuǎn)換
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
pattern:需要轉(zhuǎn)換的時(shí)間日期的格式
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") private LocalDateTime dateTime;(2)Controller
@GetMapping("date") public Object date(@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime date) {return date; }@GetMapping("date2") public Object date(@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date) {return date; }2、統(tǒng)一配置
配置文件配置
spring:jackson:date-format: yyyy-MM-dd HH:mm:ss代碼配置
RequestParam|PathVariable參數(shù)
Converter
@Configuration public class DateConfig {@Beanpublic Converter<String, LocalDate> localDateConverter() {return new Converter<>() {@Overridepublic LocalDate convert(String source) {return LocalDate.parse(source, DateTimeFormatter.ofPattern("yyyy-MM-dd"));}};}@Beanpublic Converter<String, LocalDateTime> localDateTimeConverter() {return new Converter<>() {@Overridepublic LocalDateTime convert(String source) {return LocalDateTime.parse(source, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));}};}}使用ControllerAdvice配合initBinder
@ControllerAdvice public class GlobalExceptionHandler {@InitBinderprotected void initBinder(WebDataBinder binder) {binder.registerCustomEditor(LocalDate.class, new PropertyEditorSupport() {@Overridepublic void setAsText(String text) throws IllegalArgumentException {setValue(LocalDate.parse(text, DateTimeFormatter.ofPattern("yyyy-MM-dd")));}});binder.registerCustomEditor(LocalDateTime.class, new PropertyEditorSupport() {@Overridepublic void setAsText(String text) throws IllegalArgumentException {setValue(LocalDateTime.parse(text, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));}});binder.registerCustomEditor(LocalTime.class, new PropertyEditorSupport() {@Overridepublic void setAsText(String text) throws IllegalArgumentException {setValue(LocalTime.parse(text, DateTimeFormatter.ofPattern("HH:mm:ss")));}});} }JSON格式
定義一個(gè)配置類,對(duì)ObjectMapper對(duì)象進(jìn)行定制,指定日期類對(duì)應(yīng)的序列化與反序列化處理對(duì)象
方案一
@Configuration public class LocalDateTimeFormatConfig {private static final String DEFAULT_DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";private static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd";private static final String DEFAULT_TIME_PATTERN = "HH:mm:ss";@Bean@Primarypublic ObjectMapper objectMapper(){ObjectMapper objectMapper = new ObjectMapper();JavaTimeModule javaTimeModule = new JavaTimeModule();javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_PATTERN)));javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_PATTERN)));javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_PATTERN)));javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_PATTERN)));javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_PATTERN)));javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_PATTERN)));objectMapper.registerModule(javaTimeModule);return objectMapper;} }方案二
@Configuration public class LocalDateTimeSerializerConfig {@Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")private String pattern;@Bean@Primarypublic ObjectMapper serializingObjectMapper() {ObjectMapper objectMapper = new ObjectMapper();JavaTimeModule javaTimeModule = new JavaTimeModule();javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer());javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer());objectMapper.registerModule(javaTimeModule);return objectMapper;}public class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {@Overridepublic void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers)throws IOException {gen.writeString(value.format(DateTimeFormatter.ofPattern(pattern)));}}public class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {@Overridepublic LocalDateTime deserialize(JsonParser p, DeserializationContext deserializationContext)throws IOException {return LocalDateTime.parse(p.getValueAsString(), DateTimeFormatter.ofPattern(pattern));}} }方案三?
/*** @Author ShenTuZhiGang* @Version 1.0.0* @Date 2020-03-29 19:23*/ @Configuration //@EnableWebMvc public class CustomWebMvcConfigurer implements WebMvcConfigurer {private static final String DEFAULT_DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";private static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd";private static final String DEFAULT_TIME_PATTERN = "HH:mm:ss";/*** 統(tǒng)一輸出風(fēng)格* See {@link com.fasterxml.jackson.databind.PropertyNamingStrategy.SnakeCaseStrategy} for details.* @param converters*/@Overridepublic void extendMessageConverters(List<HttpMessageConverter<?>> converters) {for (int i = 0; i < converters.size(); i++) {if (converters.get(i) instanceof MappingJackson2HttpMessageConverter) {ObjectMapper objectMapper = new ObjectMapper();// 統(tǒng)一返回?cái)?shù)據(jù)的輸出風(fēng)格objectMapper.setPropertyNamingStrategy(new PropertyNamingStrategy.SnakeCaseStrategy());objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));JavaTimeModule javaTimeModule = new JavaTimeModule();javaTimeModule.addSerializer(LocalDateTime.class,new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_PATTERN)));javaTimeModule.addSerializer(LocalDate.class,new LocalDateSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_PATTERN)));javaTimeModule.addSerializer(LocalTime.class,new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_PATTERN)));javaTimeModule.addDeserializer(LocalDateTime.class,new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_PATTERN)));javaTimeModule.addDeserializer(LocalDate.class,new LocalDateDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_PATTERN)));javaTimeModule.addDeserializer(LocalTime.class,new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_PATTERN)));objectMapper.registerModule(javaTimeModule);MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();converter.setObjectMapper(objectMapper);converters.set(i, converter);break;}}} }3、自定義配置
自定義一個(gè)反序列化類
public class DateDeserializer extends JsonDeserializer<LocalDateTime> {@Overridepublic LocalDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {if (StringUtils.isBlank(jsonParser.getText()))return null;LocalDate localDate = LocalDate.parse(jsonParser.getText(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));return LocalDateTime.of(localDate, LocalTime.MIN);} }?字段上通過(guò)com.fasterxml.jackson.databind.annotation.JsonDeserialize注解指定使用自定義的反序列化類
@JsonDeserialize(using = DateDeserializer.class) private LocalDateTime updateTime;4、完整配置
/*** @Author ShenTuZhiGang* @Version 1.0.0* @Date 2020-03-29 19:23*/ @Configuration //@EnableWebMvc public class CustomWebMvcConfigurer implements WebMvcConfigurer {private static final String DEFAULT_DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";private static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd";private static final String DEFAULT_TIME_PATTERN = "HH:mm:ss";/*** 統(tǒng)一輸出風(fēng)格* See {@link com.fasterxml.jackson.databind.PropertyNamingStrategy.SnakeCaseStrategy} for details.* @param converters*/@Overridepublic void extendMessageConverters(List<HttpMessageConverter<?>> converters) {for (int i = 0; i < converters.size(); i++) {if (converters.get(i) instanceof MappingJackson2HttpMessageConverter) {MappingJackson2HttpMessageConverter converter = (MappingJackson2HttpMessageConverter)converters.get(i);ObjectMapper objectMapper = converter.getObjectMapper();// 統(tǒng)一返回?cái)?shù)據(jù)的輸出風(fēng)格objectMapper.setPropertyNamingStrategy(new PropertyNamingStrategy.SnakeCaseStrategy());objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));break;}}}/*** LocalDate轉(zhuǎn)換器,用于轉(zhuǎn)換RequestParam和PathVariable參數(shù)*/@Beanpublic Converter<String, LocalDate> localDateConverter() {return new Converter<String, LocalDate>() {@Overridepublic LocalDate convert(String source) {return LocalDate.parse(source, DateTimeFormatter.ofPattern(DEFAULT_DATE_PATTERN));}};}/*** LocalDateTime轉(zhuǎn)換器,用于轉(zhuǎn)換RequestParam和PathVariable參數(shù)*/@Beanpublic Converter<String, LocalDateTime> localDateTimeConverter() {return new Converter<String, LocalDateTime>() {@Overridepublic LocalDateTime convert(String source) {return LocalDateTime.parse(source, DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_PATTERN));}};}/*** LocalTime轉(zhuǎn)換器,用于轉(zhuǎn)換RequestParam和PathVariable參數(shù)*/@Beanpublic Converter<String, LocalTime> localTimeConverter() {return new Converter<String, LocalTime>() {@Overridepublic LocalTime convert(String source) {return LocalTime.parse(source, DateTimeFormatter.ofPattern(DEFAULT_TIME_PATTERN));}};}/*** Date轉(zhuǎn)換器,用于轉(zhuǎn)換RequestParam和PathVariable參數(shù)*/@Beanpublic Converter<String, Date> dateConverter() {return new Converter<String, Date>() {@Overridepublic Date convert(String source) {SimpleDateFormat format = new SimpleDateFormat(DEFAULT_DATE_TIME_PATTERN);try {return format.parse(source);} catch (ParseException e) {throw new RuntimeException(e);}}};}/*** Json序列化和反序列化轉(zhuǎn)換器,用于轉(zhuǎn)換POST請(qǐng)求體中的json以及將我們的對(duì)象序列化為返回響應(yīng)的json*/@Beanpublic ObjectMapper objectMapper(){ObjectMapper objectMapper = new ObjectMapper();objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);//LocalDateTime系列序列化和反序列化模塊,繼承自jsr310,我們?cè)谶@里修改了日期格式JavaTimeModule javaTimeModule = new JavaTimeModule();javaTimeModule.addSerializer(LocalDateTime.class,new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_PATTERN)));javaTimeModule.addSerializer(LocalDate.class,new LocalDateSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_PATTERN)));javaTimeModule.addSerializer(LocalTime.class,new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_PATTERN)));javaTimeModule.addDeserializer(LocalDateTime.class,new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_PATTERN)));javaTimeModule.addDeserializer(LocalDate.class,new LocalDateDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_PATTERN)));javaTimeModule.addDeserializer(LocalTime.class,new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_PATTERN)));//Date序列化和反序列化javaTimeModule.addSerializer(Date.class, new JsonSerializer<Date>() {@Overridepublic void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {SimpleDateFormat formatter = new SimpleDateFormat(DEFAULT_DATE_TIME_PATTERN);String formattedDate = formatter.format(date);jsonGenerator.writeString(formattedDate);}});javaTimeModule.addDeserializer(Date.class, new JsonDeserializer<Date>() {@Overridepublic Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {SimpleDateFormat format = new SimpleDateFormat(DEFAULT_DATE_TIME_PATTERN);String date = jsonParser.getText();try {return format.parse(date);} catch (ParseException e) {throw new RuntimeException(e);}}});objectMapper.registerModule(javaTimeModule);return objectMapper;}}參考文章
LocalDateTime在spring boot中的格式化配置
Spring Boot(十二):LocalDateTime格式化處理
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") pattern:需要轉(zhuǎn)換的時(shí)間日期的格式
Spring中使用LocalDateTime、LocalDate等參數(shù)作為入?yún)?shù)據(jù)轉(zhuǎn)換問(wèn)題
SpringBoot在Controller中接收LocalDate/LocalDateTime
Spring Boot LocalDateTime格式處理
Springboot - 處理LocalDateTime的入?yún)⒑统鰠⒏袷?/p>
總結(jié)
以上是生活随笔為你收集整理的Spring Boot——LocalDateTime格式化配置的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Spring Boot——集成七牛云OS
- 下一篇: Spring Security——认证失