使用正则表达式解决springmvc时间格式转换问题

本文介绍如何在SpringMVC中使用正则表达式优雅地处理多种格式的时间参数,包括全局时间转换与局部时间转换两种方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、简述

使用SpringMVC接收过时间参数的程序员都应该知道,时间转换是一个令人头疼的问题,虽然这不是什么大问题,解决的方法也有多种,但解决不妥的话感觉起来会很不舒服,因为处理不当会把时间的接收格式写死,如果开发后期想更改时间格式呢?又或者项目要求可以接收不同格式的时间参数的话那又该怎么办呢?这时就可以通过正则表达式来解决这种问题了。下面就来看看如何用正则表达式优雅的解决这种问题。

二、全局时间转换

1、自定义时间转换器

/**
* 日期转换器
*/

public class DataConverter implements Converter<String, Date> {

    public Date convert(String source) {
        SimpleDateFormat sdf = getSimpleDateFormat(source);
        try {
            Date date = sdf.parse(source);
            return date;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    private SimpleDateFormat getSimpleDateFormat(String source) {
        SimpleDateFormat sdf = new SimpleDateFormat();
        if (Pattern.matches("^\\d{4}-\\d{2}-\\d{2}$", source)) { // yyyy-MM-dd
            sdf = new SimpleDateFormat("yyyy-MM-dd");
        } else if (Pattern.matches("^\\d{4}-\\d{2}-\\d{2} \\d{2}-\\d{2}-\\d{2}$", source)) { // yyyy-MM-dd HH-mm-ss
            sdf = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
        } else if (Pattern.matches("^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$", source)) { // yyyy-MM-dd HH:mm:ss
            sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        } else if (Pattern.matches("^\\d{4}/\\d{2}/\\d{2}$", source)) { // yyyy/MM/dd
            sdf = new SimpleDateFormat("yyyy/MM/dd");
        } else if (Pattern.matches("^\\d{4}/\\d{2}/\\d{2} \\d{2}/\\d{2}/\\d{2}$", source)) { // yyyy/MM/dd HH/mm/ss
            sdf = new SimpleDateFormat("yyyy/MM/dd HH/mm/ss");
        }  else if (Pattern.matches("^\\d{4}\\d{2}\\d{2}$", source)) { // yyyyMMdd
            sdf = new SimpleDateFormat("yyyyMMdd");
        }  else if (Pattern.matches("^\\d{4}\\d{2}\\d{2} \\d{2}\\d{2}\\d{2}$", source)) { // yyyyMMdd HHmmss
            sdf = new SimpleDateFormat("yyyyMMdd HHmmss");
        } else if (Pattern.matches("^\\d{4}\\.\\d{2}\\.\\d{2}$", source)) { // yyyy.MM.dd
            sdf = new SimpleDateFormat("yyyy.MM.dd");
        }  else if (Pattern.matches("^\\d{4}\\.\\d{2}\\.\\d{2} \\d{2}\\.\\d{2}\\.\\d{2}$", source)) { // yyyy.MM.dd HH.mm.ss
            sdf = new SimpleDateFormat("yyyy.MM.dd HH.mm.ss");
        }else{
            System.out.println("TypeMismatchException");
            throw new TypeMismatchException();
        }
        return sdf;
    }

}

2、注册时间转换器

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    ...

    <!-- 转换器服务工厂Bean -->
    <bean id="conversion-service"
        class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="com.lqr.convert.DataConverter" />
            </set>
        </property>
    </bean>

    <!-- 注册转化器 -->
    <mvc:annotation-driven conversion-service="conversion-service" />

</beans>

这样就可以接收绝大部分的时间格式了,如:2017-02-15、2017.02.15、2017/02/15、2017-02-15 14:20:55。。。

三、局部时间转换

局部时间转换,就是在Controller中使用@InitBinder注解一个参数类型为WebDataBinder的方法,通过WebDataBinder对象的registerCustomEditor()方法来解决时间转换问题,例子如下:

@Controller
@RequestMapping(“/test”)
public class MyController {

@RequestMapping(value = "/register.do", method = RequestMethod.POST)
public ModelAndView register(String name, Date date) throws Exception {
    ModelAndView mv = new ModelAndView();
    System.out.println("name = " + name);
    System.out.println("date = " + date);
    mv.addObject("name", name);
    mv.addObject("date", date);
    mv.setViewName("/WEB-INF/jsp/welcome.jsp");
    return mv;
}

@InitBinder
public void initBinder(WebDataBinder binder) {
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    binder.registerCustomEditor(Date.class, new CustomDateEditor(df, true));
}

}
这里的CustomDateEditor类是SpringMVC提供的,却无法获取日期数据,所以无法根据日期格式来创建不同的SimpleDateFormat对象,也就是说这种方式会把时间的格式写死,解决方法,可以自定义DateEditor。

1、创建自定义DateEditor

public class MyDateEditor extends PropertiesEditor {

@Override
public void setAsText(String source) throws IllegalArgumentException {
    SimpleDateFormat df = getSimpleDateFormat(source);
    try {
        Date date = df.parse(source);
        setValue(date);
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

private SimpleDateFormat getSimpleDateFormat(String source) {
    SimpleDateFormat sdf = new SimpleDateFormat();
    if (Pattern.matches("^\\d{4}-\\d{2}-\\d{2}$", source)) { // yyyy-MM-dd
        sdf = new SimpleDateFormat("yyyy-MM-dd");
    } else if (Pattern.matches("^\\d{4}-\\d{2}-\\d{2} \\d{2}-\\d{2}-\\d{2}$", source)) { // yyyy-MM-dd HH-mm-ss
        sdf = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
    } else if (Pattern.matches("^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$", source)) { // yyyy-MM-dd HH:mm:ss
        sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    } else if (Pattern.matches("^\\d{4}/\\d{2}/\\d{2}$", source)) { // yyyy/MM/dd
        sdf = new SimpleDateFormat("yyyy/MM/dd");
    } else if (Pattern.matches("^\\d{4}/\\d{2}/\\d{2} \\d{2}/\\d{2}/\\d{2}$", source)) { // yyyy/MM/dd HH/mm/ss
        sdf = new SimpleDateFormat("yyyy/MM/dd HH/mm/ss");
    }  else if (Pattern.matches("^\\d{4}\\d{2}\\d{2}$", source)) { // yyyyMMdd
        sdf = new SimpleDateFormat("yyyyMMdd");
    }  else if (Pattern.matches("^\\d{4}\\d{2}\\d{2} \\d{2}\\d{2}\\d{2}$", source)) { // yyyyMMdd HHmmss
        sdf = new SimpleDateFormat("yyyyMMdd HHmmss");
    } else if (Pattern.matches("^\\d{4}\\.\\d{2}\\.\\d{2}$", source)) { // yyyy.MM.dd
        sdf = new SimpleDateFormat("yyyy.MM.dd");
    }  else if (Pattern.matches("^\\d{4}\\.\\d{2}\\.\\d{2} \\d{2}\\.\\d{2}\\.\\d{2}$", source)) { // yyyy.MM.dd HH.mm.ss
        sdf = new SimpleDateFormat("yyyy.MM.dd HH.mm.ss");
    }else{
        System.out.println("TypeMismatchException");
        throw new TypeMismatchException();
    }
    return sdf;
}

}
2、使用自定义DateEditor

@Controller
@RequestMapping(“/test”)
public class MyController {

@RequestMapping(value = "/register.do", method = RequestMethod.POST)
public ModelAndView register(String name, Date date) throws Exception {
    ModelAndView mv = new ModelAndView();
    System.out.println("name = " + name);
    System.out.println("date = " + date);
    mv.addObject("name", name);
    mv.addObject("date", date);
    mv.setViewName("/WEB-INF/jsp/welcome.jsp");
    return mv;
}

@InitBinder
public void initBinder(WebDataBinder binder) {
    binder.registerCustomEditor(Date.class, new MyDateEditor());
}

}
四、总结

这两种方式我推荐使用第一种,因为是全局的,配置过一次之后,整个项目的时间参数都可以随便接收,且不需要在Controller中写任何代码,减少代码入侵。而第二种方式的优点就是不用在配置文件中做任何操作,全部由代码解决,不过是只对当前Controller生效。总的来说,使用正则表达式可以很好的解决多格式时间参数问题,如果项目中存在其他的时间格式,可以在对应的自定义时间转换器类或自定义的DateEditor中追加正则表达式以满足项目需求。

作者:优快云_LQR
链接:https://www.jianshu.com/p/f8364ea92c1d
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值