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形式的全局时间类型转换器
  */
public  class  CustomDateFormat extends StdDateFormat {
 
     private  static  final  long  serialVersionUID = -3201781773655300201L;
 
     public  static  final CustomDateFormat instance =  new  CustomDateFormat();
 
     @Override
     /**
      * 只要覆盖parse(String)这个方法即可
      */
     public  Date parse(String dateStr, ParsePosition pos) {
         return  getDate(dateStr, pos);
     }
 
     @Override
     public  Date parse(String dateStr) {
         ParsePosition pos =  new  ParsePosition(0);
         return  getDate(dateStr, pos);
     }
 
     private  Date getDate(String dateStr, ParsePosition pos) {
         SimpleDateFormat sdf =  null ;
         if  (StringUtils.isBlank(dateStr)) {
             return  null ;
         else  if  (dateStr.matches( "^\\d{4}-\\d{1,2}$" )) {
             sdf =  new  SimpleDateFormat( "yyyy-MM" );
             return  sdf.parse(dateStr, pos);
         else  if  (dateStr.matches( "^\\d{4}-\\d{1,2}-\\d{1,2}$" )) {
             sdf =  new  SimpleDateFormat( "yyyy-MM-dd" );
             return  sdf.parse(dateStr, pos);
         else  if  (dateStr.matches( "^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}$" )) {
             sdf =  new  SimpleDateFormat( "yyyy-MM-dd HH:mm" );
             return  sdf.parse(dateStr, pos);
         else  if  (dateStr.matches( "^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$" )) {
             sdf =  new  SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
             return  sdf.parse(dateStr, pos);
         else  if  (dateStr.length() == 23) {
             sdf =  new  SimpleDateFormat( "yyyy-MM-dd HH:mm:ss.SSS" );
             return  sdf.parse(dateStr, pos);
         }
         return  super.parse(dateStr, pos);
     }
 
     @Override
     public  StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition){
         SimpleDateFormat sdf =  new  SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
         return  sdf.format(date, toAppendTo, fieldPosition);
     }
 
     @Override
     public  CustomDateFormat clone() {
         return  new  CustomDateFormat();
     }
}

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
public  class  DateConverter implements Converter<String, Date> {
 
     private  static  final List<String> formarts =  new  ArrayList<>(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
     public  Date convert(String source) {
         String value = source.trim();
         if  ( "" . equals (value)) {
             return  null ;
         }
         if  (source.matches( "^\\d{4}-\\d{1,2}$" )) {
             return  parseDate(source, formarts. get (0));
         else  if  (source.matches( "^\\d{4}-\\d{1,2}-\\d{1,2}$" )) {
             return  parseDate(source, formarts. get (1));
         else  if  (source.matches( "^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}$" )) {
             return  parseDate(source, formarts. get (2));
         else  if  (source.matches( "^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$" )) {
             return  parseDate(source, formarts. get (3));
         else  {
             throw  new  IllegalArgumentException( "Invalid boolean value '"  + source +  "'" );
         }
     }
 
     /**
      * 格式化日期
      *
      * @param dateStr String 字符型日期
      * @param format  String 格式
      * @return Date 日期
      */
     private  Date parseDate(String dateStr, String format) {
         Date date =  null ;
         try  {
             DateFormat dateFormat =  new  SimpleDateFormat(format);
             date = dateFormat.parse(dateStr);
         catch  (Exception e) {
             e.printStackTrace();
         }
         return  date;
     }
 
}

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
public  class  WebMvcConfig implements WebMvcConfigurer {
 
     /**
      * 重写url路径匹配(忽略大小写敏感)
      */
     @Override
     public  void  configurePathMatch(PathMatchConfigurer configurer) {
         AntPathMatcher antPathMatcher =  new  AntPathMatcher();
         antPathMatcher.setCaseSensitive( false );
     }
 
     /**
      * JSON全局日期转换器
      */
     @Bean
     public  MappingJackson2HttpMessageConverter getMappingJackson2HttpMessageConverter() {
         MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter =  new  MappingJackson2HttpMessageConverter();
         //设置日期格式
         ObjectMapper objectMapper =  new  ObjectMapper();
         objectMapper.setDateFormat(CustomDateFormat.instance);
         objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
         mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper);
         //设置中文编码格式
         List<MediaType> list =  new  ArrayList<MediaType>();
         list.add(MediaType.APPLICATION_JSON_UTF8);
         mappingJackson2HttpMessageConverter.setSupportedMediaTypes(list);
         return  mappingJackson2HttpMessageConverter;
     }
 
     @Override
     public  void  configureMessageConverters(List<HttpMessageConverter<?>> converters){
         converters.add(getMappingJackson2HttpMessageConverter());
     }
 
     /**
      * 表单全局日期转换器
      */
     @Bean
     @Autowired
     public  ConversionService getConversionService(DateConverter dateConverter){
         ConversionServiceFactoryBean factoryBean =  new  ConversionServiceFactoryBean();
         Set<Converter> converters =  new  HashSet<>();
         converters.add(dateConverter);
         factoryBean.setConverters(converters);
         return  factoryBean.getObject();
     }
}

  从此不再纠结用@DateTimeFormat(patten = "yyyyy-MM-dd")还是@DateTimeForm

 

转载https://www.cnblogs.com/joelan0927/p/11715062.html


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM