Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions src/main/java/org/apache/commons/cli/Converter.java
Original file line number Diff line number Diff line change
Expand Up @@ -79,12 +79,17 @@ public interface Converter<T, E extends Exception> {
*/
Converter<Date, java.text.ParseException> 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);
}
};

Expand Down
8 changes: 8 additions & 0 deletions src/test/java/org/apache/commons/cli/ConverterTests.java
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
Loading