如何用DateTimeFormatter验证含可选月日的合法ISO 8601日期?
解决Java DateTimeFormatter无效月份/日期校验失效问题
问题描述
需要实现一个DateTimeFormatter,验证ISO 8601格式的日期,允许三种输入形式:仅年份、年份+月份、年份+月份+日期,同时要确保输入的日期真实有效。但现有测试用例存在以下问题:
- 验证年份或年份+月份时,无法识别
00、13这类无效月份 - 验证三种混合格式时,无效月份/日期不会触发预期的
DateTimeParseException
原测试代码
import org.junit.jupiter.api.Test; import java.time.LocalDate; import java.time.Year; import java.time.YearMonth; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatterBuilder; import java.time.format.DateTimeParseException; import java.time.format.ResolverStyle; import java.time.temporal.TemporalQuery; import static org.junit.jupiter.api.Assertions.assertThrows; public class DateTimeFormatterForStackOverflowTest { @Test public void test_year_or_year_and_month_not_valid() { DateTimeFormatter formatter = new DateTimeFormatterBuilder() .appendPattern("uuuu[-MM]") .toFormatter() .withResolverStyle(ResolverStyle.STRICT); this.expectException("1984-0", formatter, YearMonth::from, Year::from); // Doesn't throw exception. this.expectException("1984-00", formatter, YearMonth::from, Year::from); // Doesn't throw exception. this.expectException("1984-13", formatter, YearMonth::from, Year::from); // Doesn't throw exception. this.expectException("1984-99", formatter, YearMonth::from, Year::from); } @Test public void test_year_or_year_month_or_year_month_day_not_valid() { DateTimeFormatter formatter = new DateTimeFormatterBuilder() .appendPattern("[uuuu-MM-dd][uuuu-MM][uuuu]") .toFormatter() .withResolverStyle(ResolverStyle.STRICT); this.expectException("1984-0", formatter, LocalDate::from, YearMonth::from, Year::from); // Doesn't throw exception. this.expectException("1984-00", formatter, LocalDate::from, YearMonth::from, Year::from); // Doesn't throw exception. this.expectException("1984-13", formatter, LocalDate::from, YearMonth::from, Year::from); // Doesn't throw exception. this.expectException("1984-99", formatter, LocalDate::from, YearMonth::from, Year::from); this.expectException("1984-00-01", formatter, LocalDate::from, YearMonth::from, Year::from); this.expectException("1984-13-01", formatter, LocalDate::from, YearMonth::from, Year::from); this.expectException("1984-01-0", formatter, LocalDate::from, YearMonth::from, Year::from); this.expectException("1984-01-00", formatter, LocalDate::from, YearMonth::from, Year::from); this.expectException("1984-01-32", formatter, LocalDate::from, YearMonth::from, Year::from); this.expectException("1984-12-00", formatter, LocalDate::from, YearMonth::from, Year::from); this.expectException("1984-12-32", formatter, LocalDate::from, YearMonth::from, Year::from); } private void expectException(String value, DateTimeFormatter formatter, TemporalQuery<?>... queries) { assertThrows(DateTimeParseException.class, () -> formatter.parseBest(value, queries)); } }
测试失败输出
org.opentest4j.AssertionFailedError: Expected java.time.format.DateTimeParseException to be thrown, but nothing was thrown. at org.junit.jupiter.api.AssertionFailureBuilder.build(AssertionFailureBuilder.java:152) at org.junit.jupiter.api.AssertThrows.assertThrows(AssertThrows.java:73) at org.junit.jupiter.api.AssertThrows.assertThrows(AssertThrows.java:35) at org.junit.jupiter.api.Assertions.assertThrows(Assertions.java:3083) at DateTimeFormatterForStackOverflowTest.expectException(DateTimeFormatterForStackOverflowTest.java:59) at DateTimeFormatterForStackOverflowTest.test_year_or_year_month_or_year_month_day_not_valid(DateTimeFormatterForStackOverflowTest.java:43) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:566) at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:727) at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60) at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131) at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:156) at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:147) at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:86) at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(InterceptingExecutableInvoker.java:103) at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.lambda$invoke$0(InterceptingExecutableInvoker.java:93) at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106) at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64) at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45) at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37) at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.invoke(InterceptingExecutableInvoker.java:92) at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.invoke(InterceptingExecutableInvoker.java:86) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:217) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:213) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:138) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:68) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141) at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138) at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95) at org.junit.platform.engine.support.hierarchical.ForkJoinPoolHierarchicalTestExecutorService$ExclusiveTask.compute(ForkJoinPoolHierarchicalTestExecutorService.java:185) at java.base/java.util.concurrent.RecursiveAction.exec(RecursiveAction.java:189) at java.base/java.util.concurrent.ForkJoinTask.doExec$$$capture(ForkJoinTask.java:290) at java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java) at java.base/java.util.concurrent.ForkJoinPool$WorkQueue.topLevelExec(ForkJoinPool.java:1020) at java.base/java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1656) at java.base/java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1594) at java.base/java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:183)
解决思路与修正代码
问题根源
- 模式匹配逻辑缺陷:
parseBest会按传入的查询顺序尝试解析,同时格式化器的模式如果允许降级匹配(比如uuuu[-MM]会跳过无效的月份部分,只解析年份),导致无效月份未被校验。 - 模式顺序错误:在多模式匹配时,长模式放在前面会导致解析器优先尝试,但当长模式不匹配时,会直接降级到更短的模式,跳过对中间部分(如月份)的校验。
修正方案
需要强制每个输入格式被严格校验,避免解析器自动降级。可以通过以下方式实现:
- 为每种格式单独定义解析逻辑,并添加结束符校验(确保输入完全匹配格式,没有多余或缺失部分)
- 调整
parseBest的查询顺序,优先尝试更精确的类型(LocalDate>YearMonth>Year) - 使用
ResolverStyle.STRICT确保日期有效性校验生效
修正后的测试代码
import org.junit.jupiter.api.Test; import java.time.LocalDate; import java.time.Year; import java.time.YearMonth; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatterBuilder; import java.time.format.DateTimeParseException; import java.time.format.ResolverStyle; import java.time.temporal.TemporalQuery; import static org.junit.jupiter.api.Assertions.assertThrows; public class DateTimeFormatterForStackOverflowTest { @Test public void test_year_or_year_and_month_not_valid() { // 为年份+月份、年份分别定义严格模式,确保输入完全匹配 DateTimeFormatter formatter = new DateTimeFormatterBuilder() .appendPattern("uuuu-MM") .optionalStart() .parseStrict() // 强制完全匹配前面的模式 .optionalEnd() .optionalStart() .appendPattern("uuuu") .parseStrict() .optionalEnd() .toFormatter() .withResolverStyle(ResolverStyle.STRICT); this.expectException("1984-0", formatter, YearMonth::from, Year::from); this.expectException("1984-00", formatter, YearMonth::from, Year::from); this.expectException("1984-13", formatter, YearMonth::from, Year::from); this.expectException("1984-99", formatter, YearMonth::from, Year::from); } @Test public void test_year_or_year_month_or_year_month_day_not_valid() { // 按精确到粗略的顺序定义模式,每个模式都强制完全匹配 DateTimeFormatter formatter = new DateTimeFormatterBuilder() .appendPattern("uuuu-MM-dd") .optionalStart() .parseStrict() .optionalEnd() .optionalStart() .appendPattern("uuuu-MM") .parseStrict() .optionalEnd() .optionalStart() .appendPattern("uuuu") .parseStrict() .optionalEnd() .toFormatter() .withResolverStyle(ResolverStyle.STRICT); this.expectException("1984-0", formatter, LocalDate::from, YearMonth::from, Year::from); this.expectException("1984-00", formatter, LocalDate::from, YearMonth::from, Year::from); this.expectException("1984-13", formatter, LocalDate::from, YearMonth::from, Year::from); this.expectException("1984-99", formatter, LocalDate::from, YearMonth::from, Year::from); this.expectException("1984-00-01", formatter, LocalDate::from, YearMonth::from, Year::from); this.expectException("1984-13-01", formatter, LocalDate::from, YearMonth::from, Year::from); this.expectException("1984-01-0", formatter, LocalDate::from, YearMonth::from, Year::from); this.expectException("1984-01-00", formatter, LocalDate::from, YearMonth::from, Year::from); this.expectException("1984-01-32", formatter, LocalDate::from, YearMonth::from, Year::from); this.expectException("1984-12-00", formatter, LocalDate::from, YearMonth::from, Year::from); this.expectException("1984-12-32", formatter, LocalDate::from, YearMonth::from, Year::from); } private void expectException(String value, DateTimeFormatter formatter, TemporalQuery<?>... queries) { assertThrows(DateTimeParseException.class, () -> formatter.parseBest(value, queries)); } }
关键说明
parseStrict():确保输入字符串必须完全匹配当前模式,不允许部分匹配后降级到其他模式- 模式顺序:先定义最精确的格式(
uuuu-MM-dd),再依次是uuuu-MM、uuuu,确保解析器优先尝试完整格式,避免无效输入被错误匹配为短格式 ResolverStyle.STRICT:启用严格的日期校验,比如月份必须在1-12之间,日期必须符合对应月份的天数
内容的提问来源于stack exchange,提问作者hooknc
相关产品推荐
相关产品推荐

