我需要找到一个匹配两种日期格式的正则表达式:
MM/dd/yyyy and M/d/yyyy
ex. 01/31/2022, 1/1/2022, 12/13/2022, 12/1/2022
So far I try
^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9]{1}$)/[0-9]{4}$
这似乎是接近我需要的,但它仍然不完美。我在Java 7上,我需要验证用户的输入,因此我需要验证他们是否给了我正确的日期格式。例如,如果输入13/1/2022
,则SimpleDateFormat
将其转换为Sun Jan 01 00:00:00 CET 2023
。
您可以使用相同的模式"M/d/yyyy"
成功解析所有指定的日期,其中M
和d
表示最小值Month和Day的预期位数。
不需要使用正则表达式
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/d/yyyy");
System.out.println(LocalDate.parse("01/31/2022", formatter));
System.out.println(LocalDate.parse("1/1/2022", formatter));
System.out.println(LocalDate.parse("12/13/2022", formatter));
System.out.println(LocalDate.parse("12/1/2022", formatter));
输出:
2022-01-31
2022-01-01
2022-12-13
2022-12-01
在不更新JDK版本的情况下模拟Java 8 Time API功能,您可以将ThreeTen Backport库添加到您的项目中,并利用它在Java 7中实现DateTimeFormatter
和LocalDate
(感谢@Ole V.V.这个想法)。
我在Java 7上,我需要验证用户的输入,因此我需要验证他们是否给了我正确的日期格式。
对于Java 8+,我推荐Alexander Ivanchenko的答案。在Java 6或7中,你仍然可以在ThreeTen Backport库的帮助下使用这个答案,该库将java.time
API反向移植到Java 6和7。
然而,如果你不想使用ThreeTen-Backport库,而想要坚持Java标准库,你可以使用DateFormat#setLenient(boolean)
和false
作为值。
:
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class Main {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("M/d/yyyy");
sdf.setLenient(false);
String[] arr = { "01/31/2022", "1/1/2022", "12/13/2022", "12/1/2022", "13/01/2022" };
for (String s : arr) {
try {
System.out.println("==================");
sdf.parse(s);
System.out.println(s + " is a valid date");
} catch (ParseException e) {
System.out.println(e.getMessage());
// Recommended so that the caller can handle the exception appropriately
// throw new IllegalArgumentException("Invalid date");
}
}
}
}
:
==================
01/31/2022 is a valid date
==================
1/1/2022 is a valid date
==================
12/13/2022 is a valid date
==================
12/1/2022 is a valid date
==================
Unparseable date: "13/01/2022"