springmvc 日期转换器

 1 package com.xxx.common.controller.converter;
 2 
 3 import org.joda.time.DateTime;
 4 import org.joda.time.format.DateTimeFormat;
 5 import org.joda.time.format.DateTimeFormatter;
 6 import org.springframework.core.convert.converter.Converter;
 7 import org.springframework.util.StringUtils;
 8 
 9 import java.util.ArrayList;
10 import java.util.Date;
11 import java.util.List;
12 
13 /**
14  * Created by Rock 2016/12/6.
15  */
16 public class DateConverter implements Converter<String,Date> {
17 
18     private static final List<String> formarts = new ArrayList<>(4);
19 
20     static {
21         formarts.add("yyyy-MM");
22         formarts.add("yyyy-MM-dd");
23         formarts.add("yyyy-MM-dd hh:mm");
24         formarts.add("yyyy-MM-dd hh:mm:ss");
25     }
26 
27 
28     @Override
29     public Date convert(String s) {
30         if(StringUtils.isEmpty(s)){
31             return null;
32         }
33         try {
34             String formatter = "";
35             if (s.matches("^\\d{4}-\\d{1,2}$")) {
36                 formatter = formarts.get(0);
37             } else if (s.matches("^\\d{4}-\\d{1,2}-\\d{1,2}$")) {
38                 formatter = formarts.get(1);
39             } else if (s.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}$")) {
40                 formatter = formarts.get(2);
41             } else if (s.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$")) {
42                 formatter = formarts.get(3);
43             } else {
44                 throw new IllegalArgumentException("Invalid boolean value '" + s + "'");
45             }
46             DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(formatter);
47             DateTime dateTime = DateTime.parse(s,dateTimeFormatter);
48             return dateTime.toDate();
49         } catch (Exception e){
50             return null;
51         }
52     }
53 }

 springmvc.xml 配置

  <!-- 自定义日期转换器 -->
    <bean id="conversionService"
          class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <!--日期转换器 -->
                <bean class="com.xxx.common.util.DateConverter"/>
            </set>
        </property>
    </bean>

需要依赖jar包  joda-time-2.5.jar

posted @ 2017-03-27 17:07  BigNew  阅读(1662)  评论(0编辑  收藏  举报