【解决方案】Java校验14位字符串是否为正确的日期格式。

public class StringUtils {

 
    private static final ThreadLocal<DateFormat> timeFormat = new ThreadLocal<DateFormat>() {
        @Override
        protected DateFormat initialValue() {
            return new SimpleDateFormat("yyyyMMddHHmmss");
        }
    };
    
   
    public static boolean checkDate(String str) {
        try {
            if (str == null || str.length() != 14) return false;
            timeFormat.get().setLenient(false);//此处指定日期/时间解析是否不严格,在true是不严格,false时为严格
            timeFormat.get().parse(str);//从给定字符串的开始解析文本,以生成一个日期
        } catch (Exception e) {
            return false;
        }
        return true;
    }

 }

注意:如果不校验字符串长度,只校验格式,字符串:2019121314150000 将被校验通过。所以首先要校验长度。

发布了147 篇原创文章 · 获赞 88 · 访问量 14万+

猜你喜欢

转载自blog.csdn.net/zpwangshisuifeng/article/details/103545663