怎么用java判断字符是否是日期

作者:Leah

怎么用java判断字符是否是日期?这篇文章运用了实例代码展示,代码非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

1、使用正则判断是否日期public boolean isDate(String date) {

/**

* 判断日期格式和范围

*/
String rexp = "^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))";
Pattern pat = Pattern.compile(rexp);
Matcher mat = pat.matcher(date);
boolean dateType = mat.matches();
return dateType;
}

2、使用SimpleDateFormat类设置日期格式,然后通过抛出异常来判断public boolean isValidDate(String str) {

boolean convertSuccess = true;

// 指定日期格式为四位年/两位月份/两位日期,注意yyyy/MM/dd区分大小写;

//如果想判断格式为yyyy-MM-dd,需要写成-分隔符的形式

SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm");
try {
format.setLenient(false);
format.parse(str);
} catch (ParseException e) {
// e.printStackTrace();
// 如果抛出ParseException或者NullPointerException,就说明格式不对
convertSuccess = false;
}
return convertSuccess;
}

到此为止, 关于java判断字符是否是日期的方法有了一个基础的认识, 但是对于具体的使用方法还是需要多加巩固和练习。