在Java编程中,如何检查日期格式是否正确?
以下示例演示如何使用String
类的matches()
方法检查日期格式是否正确。
package com.yiibai;
public class CheckDateFormat {
public static void main(String[] argv) {
boolean isDate = false;
String date1 = "9-15-1998";
String date2 = "1997-08-16";
String datePattern = "\d{4}-\d{1,2}-\d{1,2}";
isDate = date1.matches(datePattern);
System.out.println("Date :" + date1 + ": matches with the this date Pattern:" + datePattern + "Ans:" + isDate);
isDate = date2.matches(datePattern);
System.out.println("Date :" + date2 + ": matches with the this date Pattern:" + datePattern + "Ans:" + isDate);
}
}
上述代码示例将产生以下结果 -
Date :8-05-1998: matches with the this date Pattern:d{4}-d{1,2}-d{1,2}Ans:false
Date :1997-08-16: matches with the this date Pattern:d{4}-d{1,2}-d{1,2}Ans:true
示例-2
以下是检查日期是否正确格式的另一个示例。
package com.yiibai;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CheckDateFormat2 {
public static void main(String args[]) {
List dates = new ArrayList();
dates.add("1990-12-21");
dates.add("1990-12-31");
dates.add("1990-12-32");
dates.add("09-12-12");
dates.add("2001-02-10");
String regex = "^([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|[12][0-9]|0[1-9])$";
Pattern pattern = Pattern.compile(regex);
for (Object date : dates) {
Matcher matcher = pattern.matcher((CharSequence) date);
System.out.println(date + " : " + matcher.matches());
}
}
}
上述代码示例将产生以下结果 -
1990-12-21 : true
1990-12-31 : true
1990-12-32 : false
09-12-12 : false
2001-02-10 : true