Java中日期转换

在JAVA程序中前台页面输入的日期是有限定的,要求为【2000/02/20】只有这种格式java本身才能将前台接收的数据转换为日期格式。为了让用户拥有更好的体验。一般会做格式转换。

//Converter里面两个泛型,第一个是源类型,第二个是宿类型(目标类型)
public class MyCoverter implements Converter<String , Date>{

    @Override
    public Date convert(String source) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
           return sdf.parse(source);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

上面代码实现了前台可以输入格式为【2000-02-20】的日期,但是不能输入格式为【2000/02/20】的日期了。于是想到可以通过正则表达来全面解决一下日期格式的转换。

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

        }
        return null;
    }

    private SimpleDateFormat getDataFormat(String source) {
        SimpleDateFormat sdf = new SimpleDateFormat();
        if(Pattern.matches("^\\d{4}-\\d{2}-\\d{2}$",source)){
            sdf = new SimpleDateFormat("yyyy-MM-dd");
        }else if(Pattern.matches("^\\d{4}/\\d{2}/\\d{2}$",source)){
            sdf = new SimpleDateFormat("yyyy/MM/dd");
        }else if(Pattern.matches("^\\d{4}\\d{2}\\d{2}$",source)){
            sdf = new SimpleDateFormat("yyyyMMdd");
        }else {
        //这里抛出一个异常,
            throw new TypeMismatchException("",Date.class);
        }
        return sdf;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值