View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      https://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.lang3.time;
18  
19  import static org.apache.commons.lang3.LangAssertions.assertIllegalArgumentException;
20  import static org.junit.jupiter.api.Assertions.assertEquals;
21  import static org.junit.jupiter.api.Assertions.assertFalse;
22  import static org.junit.jupiter.api.Assertions.assertNotEquals;
23  import static org.junit.jupiter.api.Assertions.assertNotNull;
24  import static org.junit.jupiter.api.Assertions.assertNull;
25  import static org.junit.jupiter.api.Assertions.assertThrows;
26  import static org.junit.jupiter.api.Assertions.assertTrue;
27  import static org.junit.jupiter.api.Assertions.fail;
28  
29  import java.io.Serializable;
30  import java.lang.reflect.Constructor;
31  import java.text.ParseException;
32  import java.text.ParsePosition;
33  import java.text.SimpleDateFormat;
34  import java.time.Instant;
35  import java.util.Calendar;
36  import java.util.Date;
37  import java.util.GregorianCalendar;
38  import java.util.HashMap;
39  import java.util.List;
40  import java.util.Locale;
41  import java.util.Map;
42  import java.util.TimeZone;
43  import java.util.stream.Stream;
44  
45  import org.apache.commons.lang3.AbstractLangTest;
46  import org.apache.commons.lang3.LocaleProblems;
47  import org.apache.commons.lang3.LocaleUtils;
48  import org.apache.commons.lang3.SerializationUtils;
49  import org.apache.commons.lang3.SystemUtils;
50  import org.apache.commons.lang3.function.TriFunction;
51  import org.apache.commons.lang3.reflect.FieldUtils;
52  import org.junit.jupiter.api.AfterEach;
53  import org.junit.jupiter.api.BeforeEach;
54  import org.junit.jupiter.api.Test;
55  import org.junit.jupiter.params.ParameterizedTest;
56  import org.junit.jupiter.params.provider.Arguments;
57  import org.junit.jupiter.params.provider.CsvSource;
58  import org.junit.jupiter.params.provider.MethodSource;
59  import org.junitpioneer.jupiter.DefaultLocale;
60  import org.junitpioneer.jupiter.DefaultTimeZone;
61  import org.junitpioneer.jupiter.ReadsDefaultLocale;
62  import org.junitpioneer.jupiter.ReadsDefaultTimeZone;
63  import org.junitpioneer.jupiter.cartesian.ArgumentSets;
64  import org.junitpioneer.jupiter.cartesian.CartesianTest;
65  import org.opentest4j.AssertionFailedError;
66  
67  /**
68   * Tests {@link FastDateParser}.
69   */
70  /* Make test reproducible */ @DefaultLocale(language = "en")
71  /* Make test reproducible */ @DefaultTimeZone(TimeZones.GMT_ID)
72  /* Make test reproducible */ @ReadsDefaultLocale
73  /* Make test reproducible */ @ReadsDefaultTimeZone
74  class FastDateParserTest extends AbstractLangTest {
75  
76      private enum Expected1806 {
77  
78          // @formatter:off
79          India(INDIA, "+05", "+0530", "+05:30", true),
80          Greenwich(TimeZones.GMT, "Z", "Z", "Z", false),
81          NewYork(NEW_YORK, "-05", "-0500", "-05:00", false);
82          // @formatter:on
83  
84          final TimeZone zone;
85          final String one;
86          final String two;
87          final String three;
88          final long offset;
89  
90          Expected1806(final TimeZone zone, final String one, final String two, final String three,
91              final boolean hasHalfHourOffset) {
92              this.zone = zone;
93              this.one = one;
94              this.two = two;
95              this.three = three;
96              this.offset = hasHalfHourOffset ? 30 * 60 * 1000 : 0;
97          }
98      }
99  
100     static final String DATE_PARSER_PARAMETERS = "dateParserParameters";
101 
102     static final String SHORT_FORMAT_NOERA = "y/M/d/h/a/m/s/E";
103 
104     static final String LONG_FORMAT_NOERA = "yyyy/MMMM/dddd/hhhh/mmmm/ss/aaaa/EEEE";
105     static final String SHORT_FORMAT = "G/" + SHORT_FORMAT_NOERA;
106     static final String LONG_FORMAT = "GGGG/" + LONG_FORMAT_NOERA;
107 
108     private static final String yMdHmsSZ = "yyyy-MM-dd'T'HH:mm:ss.SSS Z";
109     private static final String DMY_DOT = "dd.MM.yyyy";
110     private static final String YMD_SLASH = "yyyy/MM/dd";
111     private static final String MDY_DASH = "MM-DD-yyyy";
112     private static final String MDY_SLASH = "MM/DD/yyyy";
113 
114     private static final TimeZone REYKJAVIK = TimeZones.getTimeZone("Atlantic/Reykjavik");
115     private static final TimeZone NEW_YORK = TimeZones.getTimeZone("America/New_York");
116     private static final TimeZone INDIA = TimeZones.getTimeZone("Asia/Calcutta");
117 
118     private static final Locale SWEDEN = new Locale("sv", "SE");
119 
120     private static void assertParseFailure(final DateParser parser, final String source, final int errorIndex) {
121         final ParseException exception = assertThrows(ParseException.class, () -> parser.parse(source), source);
122         assertEquals(errorIndex, exception.getErrorOffset(), source);
123         for (final int startIndex : new int[] { 0, 2 }) {
124             final String input = startIndex == 0 ? source : "##" + source;
125             final ParsePosition datePosition = new ParsePosition(startIndex);
126             assertNull(parser.parse(input, datePosition), input);
127             assertEquals(startIndex + errorIndex, datePosition.getIndex(), input);
128             assertEquals(startIndex + errorIndex, datePosition.getErrorIndex(), input);
129             final ParsePosition calendarPosition = new ParsePosition(startIndex);
130             final Calendar calendar = Calendar.getInstance(TimeZones.GMT, Locale.US);
131             calendar.clear();
132             assertFalse(parser.parse(input, calendarPosition, calendar), input);
133             assertEquals(startIndex + errorIndex, calendarPosition.getIndex(), input);
134             assertEquals(startIndex + errorIndex, calendarPosition.getErrorIndex(), input);
135         }
136     }
137 
138     static void checkParse(final Locale locale, final Calendar cal, final SimpleDateFormat simpleDateFormat,
139             final DateParser dateParser) {
140         final String formattedDate = simpleDateFormat.format(cal.getTime());
141         checkParse(locale, simpleDateFormat, dateParser, formattedDate, formattedDate);
142         checkParse(locale, simpleDateFormat, dateParser, formattedDate.toLowerCase(locale), formattedDate);
143         checkParse(locale, simpleDateFormat, dateParser, formattedDate.toUpperCase(locale), formattedDate);
144     }
145 
146     static void checkParse(final Locale locale, final SimpleDateFormat simpleDateFormat, final DateParser dateParser,
147         final String formattedDate, final String originalFormattedDate) {
148         try {
149             final Date expectedTime = simpleDateFormat.parse(formattedDate);
150             final Date actualTime = dateParser.parse(formattedDate);
151             assertEquals(expectedTime, actualTime,
152                 "locale: " + locale + ", formattedDate: '" + formattedDate + "', originalFormattedDate: '"
153                     + originalFormattedDate + ", simpleDateFormat.pattern: '" + simpleDateFormat + "', Java: "
154                     + SystemUtils.JAVA_RUNTIME_VERSION + "\n");
155         } catch (final Exception e) {
156             fail("locale: " + locale + ", formattedDate: '" + formattedDate + "', error : " + e + "\n", e);
157         }
158     }
159 
160     static Stream<Arguments> dateParserParameters() {
161         return Stream.of(
162         // @formatter:off
163             Arguments.of((TriFunction<String, TimeZone, Locale, DateParser>) (format, timeZone, locale)
164                 -> new FastDateParser(format, timeZone, locale, null)),
165             Arguments.of((TriFunction<String, TimeZone, Locale, DateParser>) FastDateFormat::getInstance)
166         // @formatter:on
167         );
168     }
169 
170     private static Calendar initializeCalendar(final TimeZone timeZone) {
171         final Calendar cal = Calendar.getInstance(timeZone);
172         cal.set(Calendar.YEAR, 2001);
173         cal.set(Calendar.MONTH, 1); // not daylight savings
174         cal.set(Calendar.DAY_OF_MONTH, 4);
175         cal.set(Calendar.HOUR_OF_DAY, 12);
176         cal.set(Calendar.MINUTE, 8);
177         cal.set(Calendar.SECOND, 56);
178         cal.set(Calendar.MILLISECOND, 235);
179         return cal;
180     }
181 
182     static ArgumentSets testParsesFactory() {
183         // @formatter:off
184         return ArgumentSets
185             .argumentsForFirstParameter(LONG_FORMAT, SHORT_FORMAT)
186             .argumentsForNextParameter(LocaleUtils.availableLocaleList())
187             .argumentsForNextParameter(NEW_YORK, REYKJAVIK, TimeZones.GMT)
188             .argumentsForNextParameter(2003, 1940, 1868, 1867, 1, -1, -1940);
189         // @formatter:on
190     }
191 
192     static Stream<Arguments> weekYearParsingOutOfRangeDayOfWeekParameters() {
193         final String[][] cases = {
194             { "YYYY-'W'ww-u", "2025-W01-8" },
195             { "YYYY-'W'ww-u", "2025-W01-0" },
196             { "YYYY-'W'ww-u", "2025-W01-15" },
197             { "YYYY-'W'ww-u", "2025-W01-" + Integer.MAX_VALUE },
198             { "YYYY u", "2014 8" },
199             { "YYYY-'W'ww-u", "2025-W01-7" }, // in range, unchanged
200             { "yyyy-'W'ww-u", "2025-W01-8" }, // plain calendar year is adjusted the same way
201             { "yyyy-MM-dd u", "2014-01-06 9" },
202             { "u", "8" },
203             { "u", "0" },
204             { "u", Integer.toString(Integer.MAX_VALUE) }
205         };
206         return Stream.of(Locale.US, Locale.GERMANY)
207             .flatMap(locale -> Stream.of(cases).map(testCase -> Arguments.of(testCase[0], testCase[1], locale)));
208     }
209 
210     static Stream<Arguments> weekYearParsingStrictDayOfWeekParameters() {
211         return Stream.of(Locale.US, Locale.GERMANY)
212             .flatMap(locale -> Stream.of(0, 1, 2, 3, 4, 5, 6, 7, 8, 123, Integer.MAX_VALUE).map(dayOfWeek -> Arguments.of(dayOfWeek, locale)));
213     }
214 
215     private final TriFunction<String, TimeZone, Locale, DateParser> dateParserProvider = (format, timeZone, locale) -> new FastDateParser(format, timeZone,
216             locale, null);
217 
218     @BeforeEach
219     @AfterEach
220     void clear() {
221         AbstractFormatCache.clear();
222         FastDateFormat.clear();
223         FastDateParser.clear();
224         FastDatePrinter.clear();
225     }
226 
227     private DateParser getDateInstance(final int dateStyle, final Locale locale) {
228         return getInstance(null, AbstractFormatCache.getPatternForStyle(Integer.valueOf(dateStyle), null, locale), TimeZone.getDefault(), Locale.getDefault());
229     }
230 
231     private Calendar getEraStart(int year, final TimeZone zone, final Locale locale) {
232         final Calendar cal = Calendar.getInstance(zone, locale);
233         cal.clear();
234         // https://docs.oracle.com/javase/8/docs/technotes/guides/intl/calendar.doc.html
235         if (locale.equals(FastDateParser.JAPANESE_IMPERIAL)) {
236             if (year < 1868) {
237                 cal.set(Calendar.ERA, 0);
238                 cal.set(Calendar.YEAR, 1868 - year);
239             }
240         } else {
241             if (year < 0) {
242                 cal.set(Calendar.ERA, GregorianCalendar.BC);
243                 year = -year;
244             }
245             cal.set(Calendar.YEAR, year / 100 * 100);
246         }
247         return cal;
248     }
249 
250     DateParser getInstance(final String format) {
251         return getInstance(null, format, TimeZone.getDefault(), Locale.getDefault());
252     }
253 
254     DateParser getInstance(final String format, final Locale locale) {
255         return getInstance(null, format, TimeZone.getDefault(), locale);
256     }
257 
258     private DateParser getInstance(final String format, final TimeZone timeZone) {
259         return getInstance(null, format, timeZone, Locale.getDefault());
260     }
261 
262     /**
263      * Gets the parser instance to use for testing. Override this method in derived tests to change how instances are constructed.
264      *
265      * @param dpProvider TODO
266      * @param format The format string to use
267      * @param timeZone The time zone to use
268      * @param locale The locale to use
269      * @return The DateParser instance to use for testing
270      */
271     protected DateParser getInstance(final TriFunction<String, TimeZone, Locale, DateParser> dpProvider,
272         final String format, final TimeZone timeZone, final Locale locale) {
273         return (dpProvider == null ? this.dateParserProvider : dpProvider).apply(format, timeZone, locale);
274     }
275 
276     @ParameterizedTest
277     @MethodSource(DATE_PARSER_PARAMETERS)
278     void test_Equality_Hash(final TriFunction<String, TimeZone, Locale, DateParser> dpProvider) {
279         // @formatter:off
280         final DateParser[] parsers = {
281             getInstance(dpProvider, yMdHmsSZ, NEW_YORK, Locale.US),
282             getInstance(dpProvider, DMY_DOT, NEW_YORK, Locale.US),
283             getInstance(dpProvider, YMD_SLASH, NEW_YORK, Locale.US),
284             getInstance(dpProvider, MDY_DASH, NEW_YORK, Locale.US),
285             getInstance(dpProvider, MDY_SLASH, NEW_YORK, Locale.US),
286             getInstance(dpProvider, MDY_SLASH, REYKJAVIK, Locale.US),
287             getInstance(dpProvider, MDY_SLASH, REYKJAVIK, SWEDEN)
288         };
289         // @formatter:on
290         final Map<DateParser, Integer> map = new HashMap<>();
291         int i = 0;
292         for (final DateParser parser : parsers) {
293             map.put(parser, Integer.valueOf(i++));
294         }
295         i = 0;
296         for (final DateParser parser : parsers) {
297             assertEquals(i++, map.get(parser).intValue());
298         }
299     }
300 
301     @Test
302     @ReadsDefaultLocale
303     void test1806() throws ParseException {
304         final String formatStub = "yyyy-MM-dd'T'HH:mm:ss.SSS";
305         final String dateStub = "2001-02-04T12:08:56.235";
306         for (final Expected1806 trial : Expected1806.values()) {
307             final Calendar cal = initializeCalendar(trial.zone);
308             final String message = trial.zone.getDisplayName() + ";";
309             DateParser parser = getInstance(formatStub + "X", trial.zone);
310             assertEquals(cal.getTime().getTime(), parser.parse(dateStub + trial.one).getTime() - trial.offset, message + trial.one);
311             parser = getInstance(formatStub + "XX", trial.zone);
312             assertEquals(cal.getTime(), parser.parse(dateStub + trial.two), message + trial.two);
313             parser = getInstance(formatStub + "XXX", trial.zone);
314             assertEquals(cal.getTime(), parser.parse(dateStub + trial.three), message + trial.three);
315         }
316     }
317 
318     @Test
319     void test1806Argument() {
320         assertIllegalArgumentException(() -> getInstance("XXXX"));
321     }
322 
323     @ParameterizedTest
324     @MethodSource(DATE_PARSER_PARAMETERS)
325     void testAmPm(final TriFunction<String, TimeZone, Locale, DateParser> dpProvider) throws ParseException {
326         final Calendar cal = Calendar.getInstance(NEW_YORK, Locale.US);
327         cal.clear();
328 
329         final DateParser h = getInstance(dpProvider, "yyyy-MM-dd hh a mm:ss", NEW_YORK, Locale.US);
330         final DateParser K = getInstance(dpProvider, "yyyy-MM-dd KK a mm:ss", NEW_YORK, Locale.US);
331         final DateParser k = getInstance(dpProvider, "yyyy-MM-dd kk:mm:ss", NEW_YORK, Locale.US);
332         final DateParser H = getInstance(dpProvider, "yyyy-MM-dd HH:mm:ss", NEW_YORK, Locale.US);
333 
334         cal.set(2010, Calendar.AUGUST, 1, 0, 33, 20);
335         assertEquals(cal.getTime(), h.parse("2010-08-01 12 AM 33:20"));
336         assertEquals(cal.getTime(), K.parse("2010-08-01 0 AM 33:20"));
337         assertEquals(cal.getTime(), k.parse("2010-08-01 00:33:20"));
338         assertEquals(cal.getTime(), H.parse("2010-08-01 00:33:20"));
339 
340         cal.set(2010, Calendar.AUGUST, 1, 3, 33, 20);
341         assertEquals(cal.getTime(), h.parse("2010-08-01 3 AM 33:20"));
342         assertEquals(cal.getTime(), K.parse("2010-08-01 3 AM 33:20"));
343         assertEquals(cal.getTime(), k.parse("2010-08-01 03:33:20"));
344         assertEquals(cal.getTime(), H.parse("2010-08-01 03:33:20"));
345 
346         cal.set(2010, Calendar.AUGUST, 1, 15, 33, 20);
347         assertEquals(cal.getTime(), h.parse("2010-08-01 3 PM 33:20"));
348         assertEquals(cal.getTime(), K.parse("2010-08-01 3 PM 33:20"));
349         assertEquals(cal.getTime(), k.parse("2010-08-01 15:33:20"));
350         assertEquals(cal.getTime(), H.parse("2010-08-01 15:33:20"));
351 
352         cal.set(2010, Calendar.AUGUST, 1, 12, 33, 20);
353         assertEquals(cal.getTime(), h.parse("2010-08-01 12 PM 33:20"));
354         assertEquals(cal.getTime(), K.parse("2010-08-01 0 PM 33:20"));
355         assertEquals(cal.getTime(), k.parse("2010-08-01 12:33:20"));
356         assertEquals(cal.getTime(), H.parse("2010-08-01 12:33:20"));
357     }
358 
359     @Test
360     void testDayNumberOfWeek() throws ParseException {
361         final DateParser parser = getInstance("u");
362         final Calendar calendar = Calendar.getInstance();
363 
364         calendar.setTime(parser.parse("1"));
365         assertEquals(Calendar.MONDAY, calendar.get(Calendar.DAY_OF_WEEK));
366 
367         calendar.setTime(parser.parse("6"));
368         assertEquals(Calendar.SATURDAY, calendar.get(Calendar.DAY_OF_WEEK));
369 
370         calendar.setTime(parser.parse("7"));
371         assertEquals(Calendar.SUNDAY, calendar.get(Calendar.DAY_OF_WEEK));
372     }
373 
374     @ParameterizedTest
375     @MethodSource(DATE_PARSER_PARAMETERS)
376     void testDayOf(final TriFunction<String, TimeZone, Locale, DateParser> dpProvider) throws ParseException {
377         final Calendar cal = Calendar.getInstance(NEW_YORK, Locale.US);
378         cal.clear();
379         cal.set(2003, Calendar.FEBRUARY, 10);
380 
381         final DateParser fdf = getInstance(dpProvider, "W w F D y", NEW_YORK, Locale.US);
382         assertEquals(cal.getTime(), fdf.parse("3 7 2 41 03"));
383     }
384 
385     @Test
386     void testEquals() {
387         final DateParser parser1 = getInstance(YMD_SLASH);
388         final DateParser parser2 = getInstance(YMD_SLASH);
389 
390         assertEquals(parser1, parser2);
391         assertEquals(parser1.hashCode(), parser2.hashCode());
392 
393         assertNotEquals(parser1, new Object());
394     }
395 
396     @Test
397     void testISO8601TimeZoneVariants() throws Exception {
398         final Date date = Date.from(Instant.parse("2026-01-17T04:30:00Z"));
399         final TimeZone timeZone = TimeZone.getTimeZone("UTC");
400         assertEquals(date, new FastDateParser("yyyy-MM-dd'T'HH:mm:ssXXX", timeZone, Locale.US).parse("2026-01-17T10:00:00+05:30"));
401         assertEquals(date, new FastDateParser("yyyy-MM-dd'T'HH:mm:ssXX", timeZone, Locale.US).parse("2026-01-17T10:00:00+0530"));
402     }
403 
404     @Test
405     void testJpLocales() {
406 
407         final Calendar cal = Calendar.getInstance(TimeZones.GMT);
408         cal.clear();
409         cal.set(2003, Calendar.FEBRUARY, 10);
410         cal.set(Calendar.ERA, GregorianCalendar.BC);
411 
412         final Locale locale = LocaleUtils.toLocale("zh");
413         // ja_JP_JP cannot handle dates before 1868 properly
414 
415         final SimpleDateFormat sdf = new SimpleDateFormat(LONG_FORMAT, locale);
416         final DateParser fdf = getInstance(LONG_FORMAT, locale);
417 
418         // If parsing fails, a ParseException will be thrown and the test will fail
419         checkParse(locale, cal, sdf, fdf);
420     }
421 
422     @ParameterizedTest
423     @MethodSource(DATE_PARSER_PARAMETERS)
424     void testLANG_831(final TriFunction<String, TimeZone, Locale, DateParser> dpProvider) throws Exception {
425         testSdfAndFdp(dpProvider, "M E", "3  Tue", true);
426     }
427 
428     @ParameterizedTest
429     @MethodSource(DATE_PARSER_PARAMETERS)
430     void testLANG_832(final TriFunction<String, TimeZone, Locale, DateParser> dpProvider) throws Exception {
431         testSdfAndFdp(dpProvider, "'d'd", "d3", false); // OK
432         testSdfAndFdp(dpProvider, "'d'd'", "d3", true); // should fail (unterminated quote)
433     }
434 
435     @ParameterizedTest
436     @MethodSource(DATE_PARSER_PARAMETERS)
437     void testLang1121(final TriFunction<String, TimeZone, Locale, DateParser> dpProvider) throws ParseException {
438         final TimeZone kst = TimeZones.getTimeZone("KST");
439         final DateParser fdp = getInstance(dpProvider, "yyyyMMdd", kst, Locale.KOREA);
440 
441         assertThrows(ParseException.class, () -> fdp.parse("2015"));
442 
443         // Wed Apr 29 00:00:00 KST 2015
444         Date actual = fdp.parse("20150429");
445         final Calendar cal = Calendar.getInstance(kst, Locale.KOREA);
446         cal.clear();
447         cal.set(2015, Calendar.APRIL, 29);
448         Date expected = cal.getTime();
449         assertEquals(expected, actual);
450 
451         final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd", Locale.KOREA);
452         sdf.setTimeZone(kst);
453         expected = sdf.parse("20150429113100");
454 
455         // Thu Mar 16 00:00:00 KST 81724
456         actual = fdp.parse("20150429113100");
457         assertEquals(expected, actual);
458     }
459 
460     @ParameterizedTest
461     @MethodSource(DATE_PARSER_PARAMETERS)
462     void testLang1359(final TriFunction<String, TimeZone, Locale, DateParser> dpProvider) {
463         // A trailing numeric field is unbounded, so a digit run that overflows int must fail the parse
464         // through the ParsePosition/ParseException contract, not escape as a NumberFormatException.
465         final DateParser fdp = getInstance(dpProvider, "yyyy", TimeZones.GMT, Locale.US);
466         final String overflow = "99999999999";
467         assertThrows(ParseException.class, () -> fdp.parse(overflow));
468         final ParsePosition pos = new ParsePosition(0);
469         assertNull(fdp.parseObject(overflow, pos));
470         assertTrue(pos.getErrorIndex() >= 0);
471         assertEquals(0, pos.getIndex());
472     }
473 
474     @ParameterizedTest
475     @MethodSource(DATE_PARSER_PARAMETERS)
476     void testLang1380(final TriFunction<String, TimeZone, Locale, DateParser> dpProvider) throws ParseException {
477         final Calendar expected = Calendar.getInstance(TimeZones.GMT, Locale.FRANCE);
478         expected.clear();
479         expected.set(2014, Calendar.APRIL, 14);
480 
481         final DateParser fdp = getInstance(dpProvider, "dd MMM yyyy", TimeZones.GMT, Locale.FRANCE);
482         assertEquals(expected.getTime(), fdp.parse("14 avril 2014"));
483         assertEquals(expected.getTime(), fdp.parse("14 avr. 2014"));
484         assertEquals(expected.getTime(), fdp.parse("14 avr 2014"));
485     }
486 
487     @Test
488     void testLang303() throws ParseException {
489         DateParser parser = getInstance(YMD_SLASH);
490         final Calendar cal = Calendar.getInstance();
491         cal.set(2004, Calendar.DECEMBER, 31);
492 
493         final Date date = parser.parse("2004/11/31");
494 
495         parser = SerializationUtils.deserialize(SerializationUtils.serialize((Serializable) parser));
496         assertEquals(date, parser.parse("2004/11/31"));
497     }
498 
499     @Test
500     @ReadsDefaultLocale
501     void testLang538() throws ParseException {
502         final DateParser parser = getInstance("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", TimeZones.GMT);
503         final Calendar cal = Calendar.getInstance(TimeZones.getTimeZone("GMT-8"));
504         cal.clear();
505         cal.set(2009, Calendar.OCTOBER, 16, 8, 42, 16);
506         assertEquals(cal.getTime(), parser.parse("2009-10-16T16:42:16.000Z"));
507     }
508 
509     @ParameterizedTest
510     @MethodSource(DATE_PARSER_PARAMETERS)
511     void testLang996(final TriFunction<String, TimeZone, Locale, DateParser> dpProvider) throws ParseException {
512         final Calendar expected = Calendar.getInstance(NEW_YORK, Locale.US);
513         expected.clear();
514         expected.set(2014, Calendar.MAY, 14);
515 
516         final DateParser fdp = getInstance(dpProvider, "ddMMMyyyy", NEW_YORK, Locale.US);
517         assertEquals(expected.getTime(), fdp.parse("14may2014"));
518         assertEquals(expected.getTime(), fdp.parse("14MAY2014"));
519         assertEquals(expected.getTime(), fdp.parse("14May2014"));
520     }
521 
522     @Test
523     void testLocaleMatches() {
524         final DateParser parser = getInstance(yMdHmsSZ, SWEDEN);
525         assertEquals(SWEDEN, parser.getLocale());
526     }
527 
528     /**
529      * Tests that pre-1000AD years get padded with yyyy
530      *
531      * @throws ParseException Thrown if an operation in the test fails.
532      */
533     @Test
534     void testLowYearPadding() throws ParseException {
535         final DateParser parser = getInstance(YMD_SLASH);
536         final Calendar cal = Calendar.getInstance();
537         cal.clear();
538 
539         cal.set(1, Calendar.JANUARY, 1);
540         assertEquals(cal.getTime(), parser.parse("0001/01/01"));
541         cal.set(10, Calendar.JANUARY, 1);
542         assertEquals(cal.getTime(), parser.parse("0010/01/01"));
543         cal.set(100, Calendar.JANUARY, 1);
544         assertEquals(cal.getTime(), parser.parse("0100/01/01"));
545         cal.set(999, Calendar.JANUARY, 1);
546         assertEquals(cal.getTime(), parser.parse("0999/01/01"));
547     }
548 
549     @Test
550     void testMilleniumBug() throws ParseException {
551         final DateParser parser = getInstance(DMY_DOT);
552         final Calendar cal = Calendar.getInstance();
553         cal.clear();
554 
555         cal.set(1000, Calendar.JANUARY, 1);
556         assertEquals(cal.getTime(), parser.parse("01.01.1000"));
557     }
558 
559     @ParameterizedTest
560     @MethodSource(DATE_PARSER_PARAMETERS)
561     void testParseErrorMessageJapaneseImperial(final TriFunction<String, TimeZone, Locale, DateParser> dpProvider) {
562         // The Japanese imperial branch of parse(String) must keep the "Unparseable date" diagnostic
563         // (source text and parse position), not drop it and emit a message starting with a stray ';'.
564         final DateParser fdp = getInstance(dpProvider, "yyyy", TimeZones.GMT, FastDateParser.JAPANESE_IMPERIAL);
565         final String source = "not-a-date";
566         final ParseException e = assertThrows(ParseException.class, () -> fdp.parse(source));
567         final String message = e.getMessage();
568         assertTrue(message.startsWith("Unparseable date: '" + source + "'"), message);
569         assertTrue(message.contains("does not support dates before 1868-01-01."), message);
570     }
571 
572     @ParameterizedTest
573     @CsvSource({
574         "Z, GMT+0:99", "Z, GMT-0:99", "Z, GMT+24:00", "Z, GMT-24:00",
575         "z, GMT+0:99", "z, GMT-0:99", "z, GMT+24:00", "z, GMT-24:00"
576     })
577     void testParseInvalidGmtTimeZoneOffsets(final String zonePattern, final String offset) {
578         final String pattern = "yyyy-MM-dd'T'HH:mm:ss" + zonePattern;
579         final String prefix = "2024-01-01T00:00:00";
580         assertParseFailure(new FastDateParser(pattern, TimeZones.GMT, Locale.US), prefix + offset, prefix.length());
581         assertParseFailure(FastDateFormat.getInstance(pattern, TimeZones.GMT, Locale.US), prefix + offset, prefix.length());
582     }
583 
584     @ParameterizedTest
585     @MethodSource(DATE_PARSER_PARAMETERS)
586     void testParseInvalidTimeZoneOffsets(final TriFunction<String, TimeZone, Locale, DateParser> dpProvider) {
587         // Out-of-range offsets must not escape as IllegalArgumentException from GmtTimeZone.
588         final String prefix = "2024-01-01T00:00:00";
589         final String[][] cases = {
590             { "X", "+24", "-24", "+99", "-99" },
591             { "XX", "+2400", "-2400", "+0060", "-0060", "+9999" },
592             { "XXX", "+24:00", "-24:00", "+00:60", "-00:60", "+99:99" },
593             { "ZZ", "+24:00", "-24:00", "+00:60", "-00:60", "+99:99" },
594             { "Z", "+2400", "-2400", "+0060", "-0060" },
595             { "z", "+2400", "-2400", "+0060", "-0060" }
596         };
597         for (final String[] testCase : cases) {
598             final DateParser parser = getInstance(dpProvider, "yyyy-MM-dd'T'HH:mm:ss" + testCase[0], TimeZones.GMT, Locale.US);
599             for (int i = 1; i < testCase.length; i++) {
600                 assertParseFailure(parser, prefix + testCase[i], prefix.length());
601             }
602         }
603     }
604 
605     @ParameterizedTest
606     @MethodSource(DATE_PARSER_PARAMETERS)
607     void testParseLongShort(final TriFunction<String, TimeZone, Locale, DateParser> dpProvider)
608         throws ParseException {
609         final Calendar cal = Calendar.getInstance(NEW_YORK, Locale.US);
610         cal.clear();
611         cal.set(2003, Calendar.FEBRUARY, 10, 15, 33, 20);
612         cal.set(Calendar.MILLISECOND, 989);
613         cal.setTimeZone(NEW_YORK);
614 
615         DateParser fdf = getInstance(dpProvider, "yyyy GGGG MMMM dddd aaaa EEEE HHHH mmmm ssss SSSS ZZZZ", NEW_YORK,
616             Locale.US);
617 
618         assertEquals(cal.getTime(), fdf.parse("2003 AD February 0010 PM Monday 0015 0033 0020 0989 GMT-05:00"));
619         cal.set(Calendar.ERA, GregorianCalendar.BC);
620 
621         final Date parse = fdf.parse("2003 BC February 0010 PM Saturday 0015 0033 0020 0989 GMT-05:00");
622         assertEquals(cal.getTime(), parse);
623 
624         fdf = getInstance(null, "y G M d a E H m s S Z", NEW_YORK, Locale.US);
625         assertEquals(cal.getTime(), fdf.parse("03 BC 2 10 PM Sat 15 33 20 989 -0500"));
626 
627         cal.set(Calendar.ERA, GregorianCalendar.AD);
628         assertEquals(cal.getTime(), fdf.parse("03 AD 2 10 PM Saturday 15 33 20 989 -0500"));
629     }
630 
631     @Test
632     void testParseMissingTimeZoneName() throws ReflectiveOperationException {
633         final FastDateParser parser = new FastDateParser("yyyy-MM-dd z", TimeZones.GMT, Locale.US);
634         final List<?> patterns = parser.getPatterns();
635         final Object zonePattern = patterns.get(patterns.size() - 1);
636         final Object cachedStrategy = FieldUtils.readField(zonePattern, "strategy", true);
637         // The report supplies no concrete regex/TreeMap mismatch. Simulate a matched name missing
638         // from the lookup using a private strategy instance, leaving the shared cache untouched.
639         final Constructor<?> constructor = cachedStrategy.getClass().getDeclaredConstructor(Locale.class, Boolean.TYPE);
640         constructor.setAccessible(true);
641         final Object strategy = constructor.newInstance(Locale.US, Boolean.FALSE);
642         final Map<?, ?> names = (Map<?, ?>) FieldUtils.readField(strategy, "tzNames", true);
643         assertNotNull(names.remove("PST"));
644         FieldUtils.writeField(zonePattern, "strategy", strategy, true);
645         assertParseFailure(parser, "2024-01-01 PST", 11);
646     }
647 
648     @ParameterizedTest
649     @MethodSource(DATE_PARSER_PARAMETERS)
650     void testParseNumerics(final TriFunction<String, TimeZone, Locale, DateParser> dpProvider)
651         throws ParseException {
652         final Calendar cal = Calendar.getInstance(NEW_YORK, Locale.US);
653         cal.clear();
654         cal.set(2003, Calendar.FEBRUARY, 10, 15, 33, 20);
655         cal.set(Calendar.MILLISECOND, 989);
656 
657         final DateParser fdf = getInstance(dpProvider, "yyyyMMddHHmmssSSS", NEW_YORK, Locale.US);
658         assertEquals(cal.getTime(), fdf.parse("20030210153320989"));
659     }
660 
661     @Test
662     void testParseOffset() {
663         final DateParser parser = getInstance(YMD_SLASH);
664         final Date date = parser.parse("Today is 2015/07/04", new ParsePosition(9));
665 
666         final Calendar cal = Calendar.getInstance();
667         cal.clear();
668         cal.set(2015, Calendar.JULY, 4);
669         assertEquals(cal.getTime(), date);
670     }
671 
672     @Test
673     public void testParsePositionBeyondInputLength() {
674         final String source = "Jan";
675         final int startingIndex = 10;
676         final String[] patterns = {"yyyy", "MM", "dd", "HH", "'x'", "-", "/", ":", " 'at' ", "MMM", "EEEE", "a", "z"};
677         for (final String pattern : patterns) {
678             final DateParser parser = getInstance(pattern);
679             final ParsePosition pos1 = new ParsePosition(startingIndex);
680             final Date date = parser.parse(source, pos1);
681             assertNull(date);
682             assertEquals(startingIndex, pos1.getIndex());
683             assertEquals(startingIndex, pos1.getErrorIndex());
684             final ParsePosition pos2 = new ParsePosition(startingIndex);
685             final Calendar cal = Calendar.getInstance();
686             final boolean success = parser.parse(source, pos2, cal);
687             assertFalse(success);
688             assertEquals(startingIndex, pos2.getIndex());
689             assertEquals(startingIndex, pos2.getErrorIndex());
690         }
691     }
692 
693     @CartesianTest
694     @CartesianTest.MethodFactory("testParsesFactory")
695     // Check that all Locales can parse the formats we use
696     void testParses(final String format, final Locale locale, final TimeZone timeZone, final int year) throws Exception {
697         final Calendar cal = getEraStart(year, timeZone, locale);
698         final Date centuryStart = cal.getTime();
699         cal.set(Calendar.MONTH, 1);
700         cal.set(Calendar.DAY_OF_MONTH, 10);
701         final Date in = cal.getTime();
702         final FastDateParser fastDateParser = new FastDateParser(format, timeZone, locale, centuryStart);
703         validateSdfFormatFdpParseEquality(format, locale, timeZone, fastDateParser, in, year, centuryStart);
704     }
705 
706     /**
707      * Fails on Java 16 Early Access build 25 and above, last tested with build 36.
708      */
709     @Test
710     void testParsesKnownJava16Ea25Failure() throws Exception {
711         final String format = LONG_FORMAT;
712         final int year = 2003;
713         final Locale locale = new Locale.Builder().setLanguage("sq").setRegion("MK").build();
714         assertEquals("sq_MK", locale.toString());
715         assertNotNull(locale);
716         final TimeZone timeZone = NEW_YORK;
717         final Calendar cal = getEraStart(year, timeZone, locale);
718         final Date centuryStart = cal.getTime();
719 
720         cal.set(Calendar.MONTH, 1);
721         cal.set(Calendar.DAY_OF_MONTH, 10);
722         final Date in = cal.getTime();
723 
724         final FastDateParser fastDateParser = new FastDateParser(format, timeZone, locale, centuryStart);
725         validateSdfFormatFdpParseEquality(format, locale, timeZone, fastDateParser, in, year, centuryStart);
726     }
727 
728     @ParameterizedTest
729     @MethodSource(DATE_PARSER_PARAMETERS)
730     void testParseUnicodeTextLookupFailure(final TriFunction<String, TimeZone, Locale, DateParser> dpProvider) {
731         // Unicode regex folding accepts long s and dotted I, but the lower-case map keys differ.
732         assertParseFailure(getInstance(dpProvider, "dd MMMM yyyy", TimeZones.GMT, Locale.US), "01 Augu\u017ft 2024", 3);
733         assertParseFailure(getInstance(dpProvider, "yyyy-MM-dd EEEE", TimeZones.GMT, Locale.US), "2024-08-01 Thur\u017fday", 11);
734         assertParseFailure(getInstance(dpProvider, "yyyy-MM-dd EEEE", TimeZones.GMT, Locale.US), "2024-08-02 FR\u0130DAY", 11);
735     }
736 
737     @ParameterizedTest
738     @MethodSource(DATE_PARSER_PARAMETERS)
739     void testParseUnicodeTextLookupSuccess(final TriFunction<String, TimeZone, Locale, DateParser> dpProvider) throws ParseException {
740         final DateParser turkish = getInstance(dpProvider, "dd MMMM yyyy", TimeZones.GMT, new Locale("tr", "TR"));
741         // Root-locale fallback resolves ASCII I where Turkish lower-casing produces dotless i.
742         assertEquals(turkish.parse("01 Nisan 2024"), turkish.parse("01 NISAN 2024"));
743         final DateParser german = getInstance(dpProvider, "dd MMMM yyyy", TimeZones.GMT, Locale.GERMANY);
744         assertEquals(german.parse("01 Oktober 2024"), german.parse("01 O\u212atober 2024"));
745     }
746 
747     @ParameterizedTest
748     @MethodSource(DATE_PARSER_PARAMETERS)
749     void testParseValidTimeZoneOffsetBoundaries(final TriFunction<String, TimeZone, Locale, DateParser> dpProvider) {
750         final String prefix = "2024-01-01T00:00:00";
751         final String[][] cases = {
752             { "X", "Z", "+00", "-00", "+23", "-23" },
753             { "XX", "Z", "+0000", "-0000", "+2359", "-2359" },
754             { "XXX", "Z", "+00:00", "-00:00", "+23:59", "-23:59" },
755             { "ZZ", "Z", "+00:00", "-00:00", "+23:59", "-23:59" },
756             { "Z", "+0000", "-0000", "+2359", "-2359", "GMT+0:00", "GMT-23:59" },
757             { "z", "+0000", "-0000", "+2359", "-2359", "GMT+0:00", "GMT-23:59" }
758         };
759         for (final String[] testCase : cases) {
760             final DateParser parser = getInstance(dpProvider, "yyyy-MM-dd'T'HH:mm:ss" + testCase[0], TimeZones.GMT, Locale.US);
761             for (int i = 1; i < testCase.length; i++) {
762                 final String source = prefix + testCase[i];
763                 final ParsePosition position = new ParsePosition(0);
764                 assertNotNull(parser.parse(source, position), source);
765                 assertEquals(source.length(), position.getIndex(), source);
766                 assertEquals(-1, position.getErrorIndex(), source);
767             }
768         }
769     }
770 
771     @ParameterizedTest
772     @MethodSource(DATE_PARSER_PARAMETERS)
773     void testParseZone(final TriFunction<String, TimeZone, Locale, DateParser> dpProvider)
774         throws ParseException {
775         final Calendar cal = Calendar.getInstance(NEW_YORK, Locale.US);
776         cal.clear();
777         cal.set(2003, Calendar.JULY, 10, 16, 33, 20);
778 
779         final DateParser fdf = getInstance(dpProvider, yMdHmsSZ, NEW_YORK, Locale.US);
780 
781         assertEquals(cal.getTime(), fdf.parse("2003-07-10T15:33:20.000 -0500"));
782         assertEquals(cal.getTime(), fdf.parse("2003-07-10T15:33:20.000 GMT-05:00"));
783         assertEquals(cal.getTime(), fdf.parse("2003-07-10T16:33:20.000 Eastern Daylight Time"));
784         assertEquals(cal.getTime(), fdf.parse("2003-07-10T16:33:20.000 EDT"));
785 
786         cal.setTimeZone(TimeZones.getTimeZone("GMT-3"));
787         cal.set(2003, Calendar.FEBRUARY, 10, 9, 0, 0);
788 
789         assertEquals(cal.getTime(), fdf.parse("2003-02-10T09:00:00.000 -0300"));
790 
791         cal.setTimeZone(TimeZones.getTimeZone("GMT+5"));
792         cal.set(2003, Calendar.FEBRUARY, 10, 15, 5, 6);
793 
794         assertEquals(cal.getTime(), fdf.parse("2003-02-10T15:05:06.000 +0500"));
795     }
796 
797     @Test
798     void testPatternMatches() {
799         final DateParser parser = getInstance(yMdHmsSZ);
800         assertEquals(yMdHmsSZ, parser.getPattern());
801     }
802 
803     @ParameterizedTest
804     @MethodSource(DATE_PARSER_PARAMETERS)
805     void testQuotes(final TriFunction<String, TimeZone, Locale, DateParser> dpProvider) throws ParseException {
806         final Calendar cal = Calendar.getInstance(NEW_YORK, Locale.US);
807         cal.clear();
808         cal.set(2003, Calendar.FEBRUARY, 10, 15, 33, 20);
809         cal.set(Calendar.MILLISECOND, 989);
810 
811         final DateParser fdf = getInstance(dpProvider, "''yyyyMMdd'A''B'HHmmssSSS''", NEW_YORK, Locale.US);
812         assertEquals(cal.getTime(), fdf.parse("'20030210A'B153320989'"));
813     }
814 
815     private void testSdfAndFdp(final TriFunction<String, TimeZone, Locale, DateParser> dbProvider, final String format,
816         final String date, final boolean shouldFail) throws Exception {
817         Date dfdp = null;
818         Date dsdf = null;
819         Throwable f = null;
820         Throwable s = null;
821 
822         try {
823             final SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
824             sdf.setTimeZone(NEW_YORK);
825             dsdf = sdf.parse(date);
826             assertFalse(shouldFail, "Expected SDF failure, but got " + dsdf + " for [" + format + ", " + date + "]");
827         } catch (final Exception e) {
828             s = e;
829             if (!shouldFail) {
830                 throw e;
831             }
832         }
833 
834         try {
835             final DateParser fdp = getInstance(dbProvider, format, NEW_YORK, Locale.US);
836             dfdp = fdp.parse(date);
837             assertFalse(shouldFail, "Expected FDF failure, but got " + dfdp + " for [" + format + ", " + date + "]");
838         } catch (final Exception e) {
839             f = e;
840             if (!shouldFail) {
841                 throw e;
842             }
843         }
844         // SDF and FDF should produce equivalent results
845         assertEquals(f == null, s == null, "Should both or neither throw Exceptions");
846         assertEquals(dsdf, dfdp, "Parsed dates should be equal");
847     }
848 
849     /**
850      * Test case for {@link FastDateParser#FastDateParser(String, TimeZone, Locale)}.
851      *
852      * @throws ParseException Thrown if an operation in the test fails.
853      */
854     @Test
855     @ReadsDefaultLocale
856     @ReadsDefaultTimeZone
857     void testShortDateStyleWithLocales() throws ParseException {
858         DateParser fdf = getDateInstance(FastDateFormat.SHORT, Locale.US);
859         final Calendar cal = Calendar.getInstance();
860         cal.clear();
861 
862         cal.set(2004, Calendar.FEBRUARY, 3);
863         assertEquals(cal.getTime(), fdf.parse("2/3/04"));
864 
865         fdf = getDateInstance(FastDateFormat.SHORT, SWEDEN);
866         assertEquals(cal.getTime(), fdf.parse("2004-02-03"));
867     }
868 
869     @ParameterizedTest
870     @MethodSource(DATE_PARSER_PARAMETERS)
871     void testSpecialCharacters(final TriFunction<String, TimeZone, Locale, DateParser> dpProvider)
872         throws Exception {
873         testSdfAndFdp(dpProvider, "q", "", true); // bad pattern character (at present)
874         testSdfAndFdp(dpProvider, "Q", "", true); // bad pattern character
875         testSdfAndFdp(dpProvider, "$", "$", false); // OK
876         testSdfAndFdp(dpProvider, "?.d", "?.12", false); // OK
877         testSdfAndFdp(dpProvider, "''yyyyMMdd'A''B'HHmmssSSS''", "'20030210A'B153320989'", false); // OK
878         testSdfAndFdp(dpProvider, "''''yyyyMMdd'A''B'HHmmssSSS''", "''20030210A'B153320989'", false); // OK
879         testSdfAndFdp(dpProvider, "'$\\Ed'", "$\\Ed", false); // OK
880 
881         // quoted characters are case-sensitive
882         testSdfAndFdp(dpProvider, "'QED'", "QED", false);
883         testSdfAndFdp(dpProvider, "'QED'", "qed", true);
884         // case-sensitive after insensitive Month field
885         testSdfAndFdp(dpProvider, "yyyy-MM-dd 'QED'", "2003-02-10 QED", false);
886         testSdfAndFdp(dpProvider, "yyyy-MM-dd 'QED'", "2003-02-10 qed", true);
887     }
888 
889     /**
890      * Mutating the TimeZone passed to the constructor or returned by the getter must not change the parser.
891      */
892     @Test
893     void testTimeZoneIsCopied() throws ParseException {
894         final TimeZone timeZone = TimeZones.getTimeZone("UTC");
895         final FastDateParser parser = new FastDateParser("yyyy-MM-dd HH:mm", timeZone, Locale.US);
896         timeZone.setRawOffset(5 * 3_600_000);
897         assertEquals(new Date(0), parser.parse("1970-01-01 00:00"));
898         parser.getTimeZone().setRawOffset(5 * 3_600_000);
899         assertEquals(TimeZones.getTimeZone("UTC"), parser.getTimeZone());
900         assertEquals(new Date(0), parser.parse("1970-01-01 00:00"));
901     }
902 
903     @Test
904     @ReadsDefaultLocale
905     void testTimeZoneMatches() {
906         assertEquals(REYKJAVIK, getInstance(yMdHmsSZ, REYKJAVIK).getTimeZone());
907     }
908 
909     @Test
910     void testToStringContainsName() {
911         assertTrue(getInstance(YMD_SLASH).toString().startsWith("FastDate"));
912     }
913 
914     // we cannot use historic dates to test time zone parsing, some time zones have second offsets
915     // as well as hours and minutes which makes the z formats a low fidelity round trip
916     @ParameterizedTest
917     @MethodSource("org.apache.commons.lang3.LocaleUtils#availableLocaleList()")
918     void testTzParses(final Locale locale) throws Exception {
919         // Check that all Locales can parse the time formats we use
920         final FastDateParser fdp = new FastDateParser("yyyy/MM/dd z", TimeZone.getDefault(), locale);
921         for (final TimeZone timeZone : new TimeZone[] { NEW_YORK, REYKJAVIK, TimeZones.GMT }) {
922             final Calendar cal = Calendar.getInstance(timeZone, locale);
923             cal.clear();
924             cal.set(Calendar.YEAR, 2000);
925             cal.set(Calendar.MONTH, 1);
926             cal.set(Calendar.DAY_OF_MONTH, 10);
927             final Date expected = cal.getTime();
928             final Date actual = fdp.parse("2000/02/10 " + timeZone.getDisplayName(locale));
929             assertEquals(expected, actual, "timeZone:" + timeZone.getID() + " locale:" + locale.getDisplayName());
930         }
931     }
932 
933     @Test
934     void testWeekYearParsing() throws ParseException {
935         // 'Y' must parse as a week year (resolved through Calendar.setWeekDate), matching both SimpleDateFormat
936         // and FastDatePrinter's WeekYear rule, instead of silently mapping to the plain calendar year.
937         final String[][] cases = {
938             { "YYYY-MM-dd", "2025-12-29" }, // the ubiquitous YYYY-for-yyyy slip, at a year boundary
939             { "YYYY-'W'ww-u", "2025-W01-1" },
940             { "YYYY-'W'ww-u", "2020-W53-5" },
941             { "YYYY-'W'ww", "2024-W15" },
942             { "YY-MM-dd", "25-12-29" },
943             { "YYYY", "2025" },
944             { "yyyy-MM-dd", "2024-12-29" } // plain calendar year is unaffected
945         };
946         for (final Locale locale : new Locale[] { Locale.US, Locale.GERMANY }) {
947             for (final String[] testCase : cases) {
948                 final SimpleDateFormat sdf = new SimpleDateFormat(testCase[0], locale);
949                 final DateParser fdp = getInstance(testCase[0], locale);
950                 assertEquals(sdf.parse(testCase[1]), fdp.parse(testCase[1]),
951                         "Pattern " + testCase[0] + " input " + testCase[1] + " locale " + locale);
952             }
953         }
954     }
955 
956     @ParameterizedTest
957     @MethodSource("weekYearParsingOutOfRangeDayOfWeekParameters")
958     void testWeekYearParsingOutOfRangeDayOfWeek(final String pattern, final String input, final Locale locale) throws ParseException {
959         // An out-of-range 'u' value must be adjusted leniently like SimpleDateFormat (java.text.CalendarBuilder folds the overflow into the
960         // week number), not passed to Calendar.setWeekDate, which throws IllegalArgumentException for a day of week outside 1..7.
961         final SimpleDateFormat sdf = new SimpleDateFormat(pattern, locale);
962         final DateParser parser = getInstance(pattern, locale);
963         final Date expected = sdf.parse(input);
964         assertEquals(expected, parser.parse(input));
965         final ParsePosition pos = new ParsePosition(0);
966         assertEquals(expected, parser.parse(input, pos));
967         assertEquals(input.length(), pos.getIndex());
968         final Calendar calendar = Calendar.getInstance(parser.getTimeZone(), locale);
969         calendar.clear();
970         calendar.setLenient(true);
971         final ParsePosition calendarPos = new ParsePosition(0);
972         assertTrue(parser.parse(input, calendarPos, calendar));
973         assertEquals(expected, calendar.getTime());
974         assertEquals(input.length(), calendarPos.getIndex());
975     }
976 
977     @ParameterizedTest
978     @MethodSource("weekYearParsingStrictDayOfWeekParameters")
979     void testWeekYearParsingStrictDayOfWeek(final int dayOfWeek, final Locale locale) throws ParseException {
980         final String pattern = "YYYY-'W'ww-u";
981         final DateParser parser = getInstance(pattern, locale);
982         final SimpleDateFormat sdf = new SimpleDateFormat(pattern, locale);
983         sdf.setLenient(false);
984         final String input = "2025-W01-" + dayOfWeek;
985         final Calendar calendar = Calendar.getInstance(parser.getTimeZone(), locale);
986         calendar.clear();
987         calendar.setLenient(false);
988         final ParsePosition pos = new ParsePosition(0);
989         if (dayOfWeek >= 1 && dayOfWeek <= 7) {
990             assertTrue(parser.parse(input, pos, calendar));
991             assertEquals(sdf.parse(input), calendar.getTime());
992             assertEquals(input.length(), pos.getIndex());
993         } else {
994             // Zero must remain invalid instead of being converted to Calendar.SUNDAY.
995             assertThrows(ParseException.class, () -> sdf.parse(input));
996             assertThrows(IllegalArgumentException.class, () -> parser.parse(input, pos, calendar));
997         }
998     }
999 
1000     private void validateSdfFormatFdpParseEquality(final String formatStr, final Locale locale, final TimeZone timeZone,
1001         final FastDateParser fastDateParser, final Date inDate, final int year, final Date csDate) throws ParseException {
1002         final SimpleDateFormat sdf = new SimpleDateFormat(formatStr, locale);
1003         sdf.setTimeZone(timeZone);
1004         if (formatStr.equals(SHORT_FORMAT)) {
1005             sdf.set2DigitYearStart(csDate);
1006         }
1007         final String fmt = sdf.format(inDate);
1008 //        System.out.printf("[Java %s] Date: '%s' formatted with '%s' -> '%s'%n", SystemUtils.JAVA_RUNTIME_VERSION, inDate,
1009 //            formatStr, fmt);
1010         try {
1011             final Date out = fastDateParser.parse(fmt);
1012             assertEquals(inDate, out, "format: '" + formatStr + "', locale: '" + locale + "', time zone: '"
1013                 + timeZone.getID() + "', year: " + year + ", parse: '" + fmt);
1014         } catch (final ParseException e) {
1015             LocaleProblems.assumeLocaleSupportedB(locale, e);
1016             if (year >= 1868 || !locale.getCountry().equals("JP")) {
1017                 // LANG-978
1018                 throw new AssertionFailedError("locale " + locale, e);
1019             }
1020         }
1021     }
1022 }
1023