使用SimpleDateFormat验证日期格式

  Java中日期格式的验证有很多方式,这里介绍用 java.text.SimpleDateFormat 来实现时间验证的一种简单方式。首先我们要知道 SimpleDateFormat 对象有一个方法 void setLenient(boolean lenient) ,此方法传入一个Boolean值,表示是否是宽松的验证。当传入false时候表示验证是严格的。利用这一点我们就可以简单实现一个严格的时间格式验证。实现代码如下:

    public static boolean validDateTimeSimple(String dateTime) {
        if(dateTime == null ) {
            return false;
        }
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        df.setLenient(false);//表示严格验证
        
        try {
            df.parse(dateTime);
        } catch (ParseException e) {
            return false;
        }
        return true;
    }

  这种方式其实也是有弊端的,当dateTime字符串中间包含多余的空格的时候这种方式是无法辨别出来的,所以使用的时候需要注意。

猜你喜欢

转载自www.cnblogs.com/kemir1105/p/9074773.html