1. 程式人生 > 實用技巧 >Springboot配置全域性日期轉換器

Springboot配置全域性日期轉換器

1.Json傳參方式

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 package com.example.config; import java.text.FieldPosition; import java.text.ParsePosition; import java.text.SimpleDateFormat;
import java.util.Date; import com.fasterxml.jackson.databind.util.StdDateFormat; import org.apache.commons.lang3.StringUtils; /** * JSON形式的全域性時間型別轉換器 */ publicclassCustomDateFormat extends StdDateFormat { privatestaticfinallongserialVersionUID = -3201781773655300201L; publicstaticfinal CustomDateFormat instance =
newCustomDateFormat(); @Override /** * 只要覆蓋parse(String)這個方法即可 */ publicDate parse(String dateStr, ParsePosition pos) { returngetDate(dateStr, pos); } @Override publicDate parse(String dateStr) { ParsePosition pos =newParsePosition(0); returngetDate(dateStr, pos); } privateDate getDate(String dateStr, ParsePosition pos) {
SimpleDateFormat sdf =null; if(StringUtils.isBlank(dateStr)) { returnnull; }elseif(dateStr.matches("^\\d{4}-\\d{1,2}$")) { sdf =newSimpleDateFormat("yyyy-MM"); returnsdf.parse(dateStr, pos); }elseif(dateStr.matches("^\\d{4}-\\d{1,2}-\\d{1,2}$")) { sdf =newSimpleDateFormat("yyyy-MM-dd"); returnsdf.parse(dateStr, pos); }elseif(dateStr.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}$")) { sdf =newSimpleDateFormat("yyyy-MM-dd HH:mm"); returnsdf.parse(dateStr, pos); }elseif(dateStr.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$")) { sdf =newSimpleDateFormat("yyyy-MM-dd HH:mm:ss"); returnsdf.parse(dateStr, pos); }elseif(dateStr.length() == 23) { sdf =newSimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); returnsdf.parse(dateStr, pos); } returnsuper.parse(dateStr, pos); } @Override publicStringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition){ SimpleDateFormat sdf =newSimpleDateFormat("yyyy-MM-dd HH:mm:ss"); returnsdf.format(date, toAppendTo, fieldPosition); } @Override publicCustomDateFormat clone() { returnnewCustomDateFormat(); } }

2.表單傳參方式

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 package com.example.config; import org.springframework.core.convert.converter.Converter; import org.springframework.stereotype.Component; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * 表單形式的全域性時間型別轉換器 */ @Component publicclassDateConverter implements Converter<String, Date> { privatestaticfinal List<String> formarts =newArrayList<>(4); static{ formarts.add("yyyy-MM"); formarts.add("yyyy-MM-dd"); formarts.add("yyyy-MM-dd HH:mm"); formarts.add("yyyy-MM-dd HH:mm:ss"); } @Override publicDate convert(String source) { String value = source.trim(); if("".equals(value)) { returnnull; } if(source.matches("^\\d{4}-\\d{1,2}$")) { returnparseDate(source, formarts.get(0)); }elseif(source.matches("^\\d{4}-\\d{1,2}-\\d{1,2}$")) { returnparseDate(source, formarts.get(1)); }elseif(source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}$")) { returnparseDate(source, formarts.get(2)); }elseif(source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$")) { returnparseDate(source, formarts.get(3)); }else{ thrownewIllegalArgumentException("Invalid boolean value '"+ source +"'"); } } /** * 格式化日期 * * @param dateStr String 字元型日期 * @param format String 格式 * @return Date 日期 */ privateDate parseDate(String dateStr, String format) { Date date =null; try{ DateFormat dateFormat =newSimpleDateFormat(format); date = dateFormat.parse(dateStr); }catch(Exception e) { e.printStackTrace(); } returndate; } }

3.配置

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 package com.example.config; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.ConversionServiceFactoryBean; import org.springframework.core.convert.ConversionService; import org.springframework.core.convert.converter.Converter; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.util.AntPathMatcher; import org.springframework.web.servlet.config.annotation.PathMatchConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; @Configuration publicclassWebMvcConfig implements WebMvcConfigurer { /** * 重寫url路徑匹配(忽略大小寫敏感) */ @Override publicvoidconfigurePathMatch(PathMatchConfigurer configurer) { AntPathMatcher antPathMatcher =newAntPathMatcher(); antPathMatcher.setCaseSensitive(false); } /** * JSON全域性日期轉換器 */ @Bean publicMappingJackson2HttpMessageConverter getMappingJackson2HttpMessageConverter() { MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter =newMappingJackson2HttpMessageConverter(); //設定日期格式 ObjectMapper objectMapper =newObjectMapper(); objectMapper.setDateFormat(CustomDateFormat.instance); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper); //設定中文編碼格式 List<MediaType> list =newArrayList<MediaType>(); list.add(MediaType.APPLICATION_JSON_UTF8); mappingJackson2HttpMessageConverter.setSupportedMediaTypes(list); returnmappingJackson2HttpMessageConverter; } @Override publicvoidconfigureMessageConverters(List<HttpMessageConverter<?>> converters){ converters.add(getMappingJackson2HttpMessageConverter()); } /** * 表單全域性日期轉換器 */ @Bean @Autowired publicConversionService getConversionService(DateConverter dateConverter){ ConversionServiceFactoryBean factoryBean =newConversionServiceFactoryBean(); Set<Converter> converters =newHashSet<>(); converters.add(dateConverter); factoryBean.setConverters(converters); returnfactoryBean.getObject(); } }

  從此不再糾結用@DateTimeFormat(patten = "yyyyy-MM-dd")還是@DateTimeForm

轉載https://www.cnblogs.com/joelan0927/p/11715062.html