使用正则判断是否日期(推荐:java视频教程)public boolean isDate(String date) { String rexp = "^((\d{2}(([02468][048])|([13
使用正则判断是否日期(推荐:java视频教程)
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;
}
使用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知识请关注Java基础教程栏目。
--结束END--
本文标题: java判断是否为日期的方法(附代码)
本文链接: https://www.lsjlt.com/news/1714.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-04-03
2024-04-03
2024-04-01
2024-01-21
2024-01-21
2024-01-21
2024-01-21
2023-12-23
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0