java.time
我始终建议您使用现代 Java 日期和时间 API java.time 进行日期工作。此外,java.time 会为您提供您要求的异常。
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MM/dd/uuuu")
.withResolverStyle(ResolverStyle.LENIENT);
LocalDate date = LocalDate.parse("10/20/20128", dateFormatter);
结果:
线程“主”java.time.format.DateTimeParseException 中的异常:无法在索引 6 处解析文本“10/20/20128”
提到的索引 6是 5 位数年份在您的字符串中的位置。
这就是说,其他人建议的范围检查仍然是一个好主意。使用 java.time 这很容易。例如说我们不想接受任何未来的日期:
LocalDate date = LocalDate.parse("10/20/8012", dateFormatter);
if (date.isAfter(LocalDate.now(ZoneId.systemDefault()))) {
System.err.println("Date must not be in the future, was " + date);
}
日期不得在未来,为 8012-10-20
教程链接: Trail: Date Time(Java™ 教程)解释如何使用 java.time。