From 6332f345e3e706879b4ef692a383c646abf799a1 Mon Sep 17 00:00:00 2001 From: Naveed Khan Date: Sat, 11 Jul 2026 23:50:12 +0530 Subject: [PATCH] reject invalid dates in Converter.DATE --- src/main/java/org/apache/commons/cli/Converter.java | 9 +++++++-- src/test/java/org/apache/commons/cli/ConverterTests.java | 8 ++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/apache/commons/cli/Converter.java b/src/main/java/org/apache/commons/cli/Converter.java index a984ad04d..fcb9c43b5 100644 --- a/src/main/java/org/apache/commons/cli/Converter.java +++ b/src/main/java/org/apache/commons/cli/Converter.java @@ -79,12 +79,17 @@ public interface Converter { */ Converter DATE = s -> { final String pattern = "EEE MMM dd HH:mm:ss zzz yyyy"; + final SimpleDateFormat format = new SimpleDateFormat(pattern); + // reject out-of-range fields (for example "Feb 30") instead of silently rolling them over. + format.setLenient(false); try { - return new SimpleDateFormat(pattern).parse(s); + return format.parse(s); } catch (final java.text.ParseException e) { // Date.toString() always emits English month/day names, so fall back to Locale.ENGLISH // when the default locale rejects the documented format. - return new SimpleDateFormat(pattern, Locale.ENGLISH).parse(s); + final SimpleDateFormat englishFormat = new SimpleDateFormat(pattern, Locale.ENGLISH); + englishFormat.setLenient(false); + return englishFormat.parse(s); } }; diff --git a/src/test/java/org/apache/commons/cli/ConverterTests.java b/src/test/java/org/apache/commons/cli/ConverterTests.java index a92a13558..1f5efad55 100644 --- a/src/test/java/org/apache/commons/cli/ConverterTests.java +++ b/src/test/java/org/apache/commons/cli/ConverterTests.java @@ -104,6 +104,14 @@ void testDateLocaleDeEnglishInput() throws Exception { assertEquals(expected, Converter.DATE.apply(formatted)); } + @Test + void testDateRejectsInvalid() { + // A lenient SimpleDateFormat rolls "Feb 30" over to March 1; the converter must reject + // out-of-range fields instead of silently returning a wrong Date. + assertThrows(java.text.ParseException.class, () -> Converter.DATE.apply("Fri Feb 30 12:00:00 UTC 2024")); + assertThrows(java.text.ParseException.class, () -> Converter.DATE.apply("Mon Jan 32 00:00:00 UTC 2024")); + } + @Test void testFile() throws Exception { final URL url = this.getClass().getClassLoader().getResource("./org/apache/commons/cli/existing-readable.file");