java检查字符串是否是合法的日期格式

校验字符串是否是日期

如文章标题,代码如下:

	/**
     * 检查日期格式是否合法
     *
     * @param str 日期字符串
     * @return boolean
     */
    private static boolean isValidDate(String str) {
        boolean convertSuccess = true;
        // 指定日期格式为四位年/两位月份/两位日期,注意yyyy/MM/dd区分大小写,可扩展到时分秒;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期,比如2007/02/29会被接受,并转换成2007/03/01
            format.setLenient(false);
            format.parse(str.intern());
        } catch (ParseException e) {
            // 如果throw java.text.ParseException或者NullPointerException,就说明格式不对
            convertSuccess = false;
        }
        return convertSuccess;
    }
发布了42 篇原创文章 · 获赞 10 · 访问量 7063

猜你喜欢

转载自blog.csdn.net/MCJPAO/article/details/96099459