时间格式一: yyyy-MM-dd HH:mm:ss
正则表达式为:
(19|20)\\d\\d\\-(0[1-9]|1[012])\\-(0[1-9]|[12][0-9]|3[01]) ([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])
测试代码:
import java.util.regex.Pattern;
public class CheckDate {
public static void main(String[] args) {
test();
}
public static void test() {
String timeRegex = "(19|20)\\d\\d\\-(0[1-9]|1[012])\\-(0[1-9]|[12][0-9]|3[01]) ([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])";
boolean date= Pattern.matches(timeRegex, "2023-02-29 23:48:59");
System.out.println("timeRex : match : " + date);
}
}
时间格式二: yyyyMMddHHmmss
正则表达式为:
^[1-9]\\d{3}(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])([0-1][0-9]|2[0-3])([0-5][0-9])([0-5][0-9])$
测试代码:
import java.util.regex.Pattern;
public class CheckDate {
public static void main(String[] args) {
test();
}
public static void test() {
String timeRegex = "^[1-9]\d{3}(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])([0-1][0-9]|2[0-3])([0-5][0-9])([0-5][0-9])$";
boolean date= Pattern.matches(timeRegex, "20230229234859");
System.out.println("timeRex : match : " + date);
}
}