• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (C) 2016 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
3 /********************************************************************
4  * COPYRIGHT:
5  * Copyright (c) 1997-2016, International Business Machines Corporation and
6  * others. All Rights Reserved.
7  ********************************************************************/
8 
9 #include "unicode/utypes.h"
10 
11 #if !UCONFIG_NO_FORMATTING
12 #include "dtfmrgts.h"
13 
14 #include "unicode/timezone.h"
15 #include "unicode/gregocal.h"
16 #include "unicode/smpdtfmt.h"
17 #include "unicode/datefmt.h"
18 #include "unicode/simpletz.h"
19 #include "unicode/resbund.h"
20 #include "cmemory.h"
21 
22 // *****************************************************************************
23 // class DateFormatRegressionTest
24 // *****************************************************************************
25 
26 #define CASE(id,test) case id: name = #test; if (exec) { logln(#test "---"); logln((UnicodeString)""); test(); } break;
27 
28 void
runIndexedTest(int32_t index,UBool exec,const char * & name,char *)29 DateFormatRegressionTest::runIndexedTest( int32_t index, UBool exec, const char* &name, char* /*par*/ )
30 {
31     // if (exec) logln((UnicodeString)"TestSuite DateFormatRegressionTest");
32     switch (index) {
33         CASE(0,Test4029195)
34         CASE(1,Test4052408)
35         CASE(2,Test4056591)
36         CASE(3,Test4059917)
37         CASE(4,Test4060212)
38         CASE(5,Test4061287)
39         CASE(6,Test4065240)
40         CASE(7,Test4071441)
41         CASE(8,Test4073003)
42         CASE(9,Test4089106)
43         CASE(10,Test4100302)
44         CASE(11,Test4101483)
45         CASE(12,Test4103340)
46         CASE(13,Test4103341)
47         CASE(14,Test4104136)
48         CASE(15,Test4104522)
49         CASE(16,Test4106807)
50         CASE(17,Test4108407)
51         CASE(18,Test4134203)
52         CASE(19,Test4151631)
53         CASE(20,Test4151706)
54         CASE(21,Test4162071)
55         CASE(22,Test4182066)
56         CASE(23,Test4210209)
57         CASE(24,Test714)
58         CASE(25,Test1684)
59         CASE(26,Test5554)
60         CASE(27,Test9237)
61         CASE(28,TestParsing)
62         CASE(29,TestT10334)
63         CASE(30,TestT10619)
64         CASE(31,TestT10855)
65         CASE(32,TestT10906)
66         default: name = ""; break;
67     }
68 }
69 
70 /**
71  * @bug 4029195
72  */
Test4029195(void)73 void DateFormatRegressionTest::Test4029195(void)
74 {
75     UErrorCode status = U_ZERO_ERROR;
76 
77     UDate today = Calendar::getNow();
78     logln((UnicodeString) "today: " + today);
79 
80     SimpleDateFormat *sdf = (SimpleDateFormat*) DateFormat::createDateInstance();
81     if (failure(status, "SimpleDateFormat::createDateInstance")) {
82         return;
83     }
84     UnicodeString pat;
85     if(sdf == NULL){
86         dataerrln("Error calling DateFormat::createDateTimeInstance");
87         return;
88     }
89 
90     pat = sdf->toPattern(pat);
91     logln("pattern: " + pat);
92     UnicodeString fmtd;
93 
94     FieldPosition pos(FieldPosition::DONT_CARE);
95     fmtd = sdf->format(today, fmtd, pos);
96     logln("today: " + fmtd);
97 
98     sdf->applyPattern("G yyyy DDD");
99     UnicodeString todayS;
100     todayS = sdf->format(today, todayS, pos);
101     logln("today: " + todayS);
102     //try {
103         today = sdf->parse(todayS, status);
104         failure(status, "sdf->parse");
105         logln((UnicodeString)"today date: " + today);
106     /*} catch(Exception e) {
107         logln("Error reparsing date: " + e.getMessage());
108     }*/
109 
110     //try {
111         UnicodeString rt;
112         rt = sdf->format(sdf->parse(todayS, status), rt, pos);
113         failure(status, "sdf->parse");
114         logln("round trip: " + rt);
115         if(rt != todayS)
116             errln("Fail: Want " + todayS + " Got " + rt);
117     /*}
118     catch (ParseException e) {
119         errln("Fail: " + e);
120         e.printStackTrace();
121     }*/
122 
123     delete sdf;
124 }
125 
126 /**
127  * @bug 4052408
128  */
Test4052408(void)129 void DateFormatRegressionTest::Test4052408(void)
130 {
131 
132     DateFormat *fmt = DateFormat::createDateTimeInstance(DateFormat::SHORT,
133                                                 DateFormat::SHORT, Locale::getUS());
134     if (fmt == NULL) {
135         dataerrln("Error calling DateFormat::createDateTimeInstance");
136         return;
137     }
138 
139     UDate dt = date(97, UCAL_MAY, 3, 8, 55);
140     UnicodeString str;
141     str = fmt->format(dt, str);
142     logln(str);
143 
144     if(str != "5/3/97, 8:55 AM")
145         errln("Fail: Test broken; Want 5/3/97 8:55 AM Got " + str);
146 
147     UnicodeString expected[] = {
148         (UnicodeString) "", //"ERA_FIELD",
149         (UnicodeString) "97", //"YEAR_FIELD",
150         (UnicodeString) "5", //"MONTH_FIELD",
151         (UnicodeString) "3", //"DATE_FIELD",
152         (UnicodeString) "", //"HOUR_OF_DAY1_FIELD",
153         (UnicodeString) "", //"HOUR_OF_DAY0_FIELD",
154         (UnicodeString) "55", //"MINUTE_FIELD",
155         (UnicodeString) "", //"SECOND_FIELD",
156         (UnicodeString) "", //"MILLISECOND_FIELD",
157         (UnicodeString) "", //"DAY_OF_WEEK_FIELD",
158         (UnicodeString) "", //"DAY_OF_YEAR_FIELD",
159         (UnicodeString) "", //"DAY_OF_WEEK_IN_MONTH_FIELD",
160         (UnicodeString) "", //"WEEK_OF_YEAR_FIELD",
161         (UnicodeString) "", //"WEEK_OF_MONTH_FIELD",
162         (UnicodeString) "AM", //"AM_PM_FIELD",
163         (UnicodeString) "8", //"HOUR1_FIELD",
164         (UnicodeString) "", //"HOUR0_FIELD",
165         (UnicodeString) "" //"TIMEZONE_FIELD"
166     };
167 
168     //Hashtable expected;// = new Hashtable();
169     //expected.put(new LongKey(DateFormat.MONTH_FIELD), "5");
170     //expected.put(new LongKey(DateFormat.DATE_FIELD), "3");
171     //expected.put(new LongKey(DateFormat.YEAR_FIELD), "97");
172     //expected.put(new LongKey(DateFormat.HOUR1_FIELD), "8");
173     //expected.put(new LongKey(DateFormat.MINUTE_FIELD), "55");
174     //expected.put(new LongKey(DateFormat.AM_PM_FIELD), "AM");
175 
176     //StringBuffer buf = new StringBuffer();
177     UnicodeString fieldNames[] = {
178         (UnicodeString) "ERA_FIELD",
179         (UnicodeString) "YEAR_FIELD",
180         (UnicodeString) "MONTH_FIELD",
181         (UnicodeString) "DATE_FIELD",
182         (UnicodeString) "HOUR_OF_DAY1_FIELD",
183         (UnicodeString) "HOUR_OF_DAY0_FIELD",
184         (UnicodeString) "MINUTE_FIELD",
185         (UnicodeString) "SECOND_FIELD",
186         (UnicodeString) "MILLISECOND_FIELD",
187         (UnicodeString) "DAY_OF_WEEK_FIELD",
188         (UnicodeString) "DAY_OF_YEAR_FIELD",
189         (UnicodeString) "DAY_OF_WEEK_IN_MONTH_FIELD",
190         (UnicodeString) "WEEK_OF_YEAR_FIELD",
191         (UnicodeString) "WEEK_OF_MONTH_FIELD",
192         (UnicodeString) "AM_PM_FIELD",
193         (UnicodeString) "HOUR1_FIELD",
194         (UnicodeString) "HOUR0_FIELD",
195         (UnicodeString) "TIMEZONE_FIELD"
196     };
197 
198     UBool pass = TRUE;
199     for(int i = 0; i <= 17; ++i) {
200         FieldPosition pos(i);
201         UnicodeString buf;
202         fmt->format(dt, buf, pos);
203         //char[] dst = new char[pos.getEndIndex() - pos.getBeginIndex()];
204         UnicodeString dst;
205         buf.extractBetween(pos.getBeginIndex(), pos.getEndIndex(), dst);
206         UnicodeString str(dst);
207         logln((UnicodeString)"" + i + (UnicodeString)": " + fieldNames[i] +
208                 (UnicodeString)", \"" + str + (UnicodeString)"\", " +
209                 pos.getBeginIndex() + (UnicodeString)", " +
210                 pos.getEndIndex());
211         UnicodeString exp = expected[i];
212         if((exp.length() == 0 && str.length() == 0) || str == exp)
213             logln(" ok");
214         else {
215             errln(UnicodeString(" expected ") + exp);
216             pass = FALSE;
217         }
218 
219     }
220     if( ! pass)
221         errln("Fail: FieldPosition not set right by DateFormat");
222 
223     delete fmt;
224 }
225 
226 /**
227  * @bug 4056591
228  * Verify the function of the [s|g]et2DigitYearStart() API.
229  */
Test4056591(void)230 void DateFormatRegressionTest::Test4056591(void)
231 {
232     UErrorCode status = U_ZERO_ERROR;
233 
234     //try {
235         SimpleDateFormat *fmt = new SimpleDateFormat(UnicodeString("yyMMdd"), Locale::getUS(), status);
236         if (failure(status, "new SimpleDateFormat", TRUE)) {
237             delete fmt;
238             return;
239         }
240         UDate start = date(1809-1900, UCAL_DECEMBER, 25);
241         fmt->set2DigitYearStart(start, status);
242         failure(status, "fmt->setTwoDigitStartDate");
243         if( (fmt->get2DigitYearStart(status) != start) || failure(status, "get2DigitStartDate"))
244             errln("get2DigitYearStart broken");
245         UDate dates [] = {
246             date(1809-1900, UCAL_DECEMBER, 25),
247             date(1909-1900, UCAL_DECEMBER, 24),
248             date(1809-1900, UCAL_DECEMBER, 26),
249             date(1861-1900, UCAL_DECEMBER, 25),
250         };
251 
252         UnicodeString strings [] = {
253             (UnicodeString) "091225",
254             (UnicodeString) "091224",
255             (UnicodeString) "091226",
256             (UnicodeString) "611225"
257         };
258 
259         /*Object[] DATA = {
260             "091225", new Date(1809-1900, Calendar.DECEMBER, 25),
261             "091224", new Date(1909-1900, Calendar.DECEMBER, 24),
262             "091226", new Date(1809-1900, Calendar.DECEMBER, 26),
263             "611225", new Date(1861-1900, Calendar.DECEMBER, 25),
264         };*/
265 
266         for(int i = 0; i < 4; i++) {
267             UnicodeString s = strings[i];
268             UDate exp = dates[i];
269             UDate got = fmt->parse(s, status);
270             failure(status, "fmt->parse");
271             logln(s + " -> " + got + "; exp " + exp);
272             if(got != exp)
273                 errln("set2DigitYearStart broken");
274         }
275     /*}
276     catch (ParseException e) {
277         errln("Fail: " + e);
278         e.printStackTrace();
279     }*/
280 
281     delete fmt;
282 }
283 
284 /**
285  * @bug 4059917
286  */
Test4059917(void)287 void DateFormatRegressionTest::Test4059917(void)
288 {
289     UErrorCode status = U_ZERO_ERROR;
290 
291     SimpleDateFormat *fmt;
292     UnicodeString myDate;
293 
294     fmt = new SimpleDateFormat( UnicodeString("yyyy/MM/dd"), status );
295     if (failure(status, "new SimpleDateFormat", TRUE)) return;
296     myDate = "1997/01/01";
297     aux917( fmt, myDate );
298 
299     delete fmt;
300     fmt = NULL;
301 
302     fmt = new SimpleDateFormat( UnicodeString("yyyyMMdd"), status );
303     if(failure(status, "new SimpleDateFormat")) return;
304     myDate = "19970101";
305     aux917( fmt, myDate );
306 
307     delete fmt;
308 }
309 
aux917(SimpleDateFormat * fmt,UnicodeString & str)310 void DateFormatRegressionTest::aux917( SimpleDateFormat *fmt, UnicodeString& str ) {
311     //try {
312     UnicodeString pat;
313     pat = fmt->toPattern(pat);
314     logln( "==================" );
315     logln( "testIt: pattern=" + pat +
316                " string=" + str );
317 
318 
319     Formattable o;
320     //Object o;
321     ParsePosition pos(0);
322     fmt->parseObject( str, o, pos );
323     //logln( UnicodeString("Parsed object: ") + o );
324 
325     UErrorCode status = U_ZERO_ERROR;
326     UnicodeString formatted;
327     FieldPosition poss(FieldPosition::DONT_CARE);
328     formatted = fmt->format( o, formatted, poss, status );
329     failure(status, "fmt->format");
330     logln( "Formatted string: " + formatted );
331     if( formatted != str)
332         errln("Fail: Want " + str + " Got " + formatted);
333     /*}
334     catch (ParseException e) {
335         errln("Fail: " + e);
336         e.printStackTrace();
337     }*/
338 }
339 
340 /**
341  * @bug 4060212
342  */
Test4060212(void)343 void DateFormatRegressionTest::Test4060212(void)
344 {
345     UnicodeString dateString = "1995-040.05:01:29";
346 
347     logln( "dateString= " + dateString );
348     logln("Using yyyy-DDD.hh:mm:ss");
349     UErrorCode status = U_ZERO_ERROR;
350     SimpleDateFormat *formatter = new SimpleDateFormat(UnicodeString("yyyy-DDD.hh:mm:ss"), status);
351     if (failure(status, "new SimpleDateFormat", TRUE)) return;
352     ParsePosition pos(0);
353     UDate myDate = formatter->parse( dateString, pos );
354     UnicodeString myString;
355     DateFormat *fmt = DateFormat::createDateTimeInstance( DateFormat::FULL,
356                                                             DateFormat::LONG);
357     if (fmt == NULL) {
358         dataerrln("Error calling DateFormat::createDateTimeInstance");
359         delete formatter;
360         return;
361     }
362 
363     myString = fmt->format( myDate, myString);
364     logln( myString );
365 
366     Calendar *cal = new GregorianCalendar(status);
367     failure(status, "new GregorianCalendar");
368     cal->setTime(myDate, status);
369     failure(status, "cal->setTime");
370     if ((cal->get(UCAL_DAY_OF_YEAR, status) != 40) || failure(status, "cal->get"))
371         errln((UnicodeString) "Fail: Got " + cal->get(UCAL_DAY_OF_YEAR, status) +
372                             " Want 40");
373 
374     // this is an odd usage of "ddd" and it doesn't
375     // work now that date values are range checked per #3579.
376     logln("Using yyyy-ddd.hh:mm:ss");
377     delete formatter;
378     formatter = NULL;
379     formatter = new SimpleDateFormat(UnicodeString("yyyy-ddd.hh:mm:ss"), status);
380     if(failure(status, "new SimpleDateFormat")) return;
381     pos.setIndex(0);
382     myDate = formatter->parse( dateString, pos );
383     myString = fmt->format( myDate, myString );
384     logln( myString );
385     cal->setTime(myDate, status);
386     failure(status, "cal->setTime");
387     if ((cal->get(UCAL_DAY_OF_YEAR, status) != 40) || failure(status, "cal->get"))
388         errln((UnicodeString) "Fail: Got " + cal->get(UCAL_DAY_OF_YEAR, status) +
389                             " Want 40");
390 
391     delete formatter;
392     delete fmt;
393     delete cal;
394 }
395 
396 /**
397  * @bug 4061287
398  */
Test4061287(void)399 void DateFormatRegressionTest::Test4061287(void)
400 {
401     UErrorCode status = U_ZERO_ERROR;
402 
403     SimpleDateFormat *df = new SimpleDateFormat(UnicodeString("dd/MM/yyyy"), status);
404     if (U_FAILURE(status)) {
405         dataerrln("Fail new SimpleDateFormat: %s", u_errorName(status));
406         delete df;
407         return;
408     }
409     failure(status, "new SimpleDateFormat");
410     //try {
411     logln(UnicodeString("") + df->parse("35/01/1971", status));
412     failure(status, "df->parse(\"35/01/1971\")");
413     //logln(df.parse("35/01/1971").toString());
414     //}
415     /*catch (ParseException e) {
416         errln("Fail: " + e);
417         e.printStackTrace();
418     }*/
419     df->setLenient(FALSE);
420     UBool ok = FALSE;
421     //try {
422     logln(UnicodeString("") + df->parse("35/01/1971", status));
423     if(U_FAILURE(status))
424         ok = TRUE;
425     //logln(df.parse("35/01/1971").toString());
426     //} catch (ParseException e) {ok=TRUE;}
427     if(!ok)
428         errln("Fail: Lenient not working");
429     delete df;
430 }
431 
432 /**
433  * @bug 4065240
434  */
Test4065240(void)435 void DateFormatRegressionTest::Test4065240(void)
436 {
437     UDate curDate;
438     DateFormat *shortdate, *fulldate;
439     UnicodeString strShortDate, strFullDate;
440     Locale saveLocale = Locale::getDefault();
441     TimeZone *saveZone = TimeZone::createDefault();
442 
443     UErrorCode status = U_ZERO_ERROR;
444     //try {
445         Locale *curLocale = new Locale("de","DE");
446         Locale::setDefault(*curLocale, status);
447         failure(status, "Locale::setDefault");
448         // {sfb} adoptDefault instead of setDefault
449         //TimeZone::setDefault(TimeZone::createTimeZone("EST"));
450         TimeZone::adoptDefault(TimeZone::createTimeZone("EST"));
451         curDate = date(98, 0, 1);
452         shortdate = DateFormat::createDateInstance(DateFormat::SHORT);
453         if (shortdate == NULL){
454             dataerrln("Error calling DateFormat::createDateInstance");
455             return;
456         }
457 
458         fulldate = DateFormat::createDateTimeInstance(DateFormat::LONG, DateFormat::LONG);
459         if (fulldate == NULL){
460             dataerrln("Error calling DateFormat::createDateTimeInstance");
461             return;
462         }
463         strShortDate = "The current date (short form) is ";
464         UnicodeString temp;
465         temp = shortdate->format(curDate, temp);
466         strShortDate += temp;
467         strFullDate = "The current date (long form) is ";
468         UnicodeString temp2;
469         fulldate->format(curDate, temp2);
470         strFullDate += temp2;
471 
472         logln(strShortDate);
473         logln(strFullDate);
474 
475         // {sfb} What to do with resource bundle stuff?????
476 
477         // Check to see if the resource is present; if not, we can't test
478         ResourceBundle *bundle = new ResourceBundle(
479             NULL, *curLocale, status);
480         failure(status, "new ResourceBundle");
481             //(UnicodeString) "java.text.resources.DateFormatZoneData", curLocale);
482 
483         // {sfb} API change to ResourceBundle -- add getLocale()
484         /*if (bundle->getLocale().getLanguage(temp) == UnicodeString("de")) {
485             // UPDATE THIS AS ZONE NAME RESOURCE FOR <EST> in de_DE is updated
486             if (!strFullDate.endsWith(UnicodeString("GMT-05:00")))
487                 errln("Fail: Want GMT-05:00");
488         }
489         else {
490             logln("*** TEST COULD NOT BE COMPLETED BECAUSE DateFormatZoneData ***");
491             logln("*** FOR LOCALE de OR de_DE IS MISSING ***");
492         }*/
493     //}
494     //finally {
495     Locale::setDefault(saveLocale, status);
496     failure(status, "Locale::setDefault");
497     TimeZone::setDefault(*saveZone);
498     //}
499     delete shortdate;
500     delete fulldate;
501     delete saveZone;
502     delete curLocale;
503     delete bundle;
504 }
505 
506 /*
507   DateFormat.equals is too narrowly defined.  As a result, MessageFormat
508   does not work correctly.  DateFormat.equals needs to be written so
509   that the Calendar sub-object is not compared using Calendar.equals,
510   but rather compared for equivalency.  This may necessitate adding a
511   (package private) method to Calendar to test for equivalency.
512 
513   Currently this bug breaks MessageFormat.toPattern
514   */
515 /**
516  * @bug 4071441
517  */
Test4071441(void)518 void DateFormatRegressionTest::Test4071441(void)
519 {
520     DateFormat *fmtA = DateFormat::createInstance();
521     DateFormat *fmtB = DateFormat::createInstance();
522 
523     if (fmtA == NULL || fmtB == NULL){
524         dataerrln("Error calling DateFormat::createInstance");
525         delete fmtA;
526         delete fmtB;
527         return;
528     }
529 
530     // {sfb} Is it OK to cast away const here?
531     Calendar *calA = (Calendar*) fmtA->getCalendar();
532     Calendar *calB = (Calendar*) fmtB->getCalendar();
533     if(!calA || !calB) {
534       errln("Couldn't get proper calendars, exiting");
535       delete fmtA;
536       delete fmtB;
537       return;
538     }
539     UDate epoch = date(0, 0, 0);
540     UDate xmas = date(61, UCAL_DECEMBER, 25);
541 
542     UErrorCode status = U_ZERO_ERROR;
543     calA->setTime(epoch, status);
544     failure(status, "calA->setTime");
545     calB->setTime(epoch, status);
546     failure(status, "calB->setTime");
547     if (*calA != *calB)
548         errln("Fail: Can't complete test; Calendar instances unequal");
549     if (*fmtA != *fmtB)
550         errln("Fail: DateFormat unequal when Calendars equal");
551     calB->setTime(xmas, status);
552     failure(status, "calB->setTime");
553     if (*calA == *calB)
554         errln("Fail: Can't complete test; Calendar instances equal");
555     if (*fmtA != *fmtB)
556         errln("Fail: DateFormat unequal when Calendars equivalent");
557 
558     logln("DateFormat.equals ok");
559 
560     delete fmtA;
561     delete fmtB;
562 }
563 
564 /* The java.text.DateFormat.parse(String) method expects for the
565   US locale a string formatted according to mm/dd/yy and parses it
566   correctly.
567 
568   When given a string mm/dd/yyyy [sic] it only parses up to the first
569   two y's, typically resulting in a date in the year 1919.
570 
571   Please extend the parsing method(s) to handle strings with
572   four-digit year values (probably also applicable to various
573   other locales.  */
574 /**
575  * @bug 4073003
576  */
Test4073003(void)577 void DateFormatRegressionTest::Test4073003(void)
578 {
579     //try {
580     UErrorCode ec = U_ZERO_ERROR;
581     SimpleDateFormat fmt("MM/dd/yy", Locale::getUK(), ec);
582     if (U_FAILURE(ec)) {
583         dataerrln("FAIL: SimpleDateFormat constructor - %s", u_errorName(ec));
584         return;
585     }
586         UnicodeString tests [] = {
587             (UnicodeString) "12/25/61",
588             (UnicodeString) "12/25/1961",
589             (UnicodeString) "4/3/2010",
590             (UnicodeString) "4/3/10"
591         };
592         UErrorCode status = U_ZERO_ERROR;
593         for(int i= 0; i < 4; i+=2) {
594             UDate d = fmt.parse(tests[i], status);
595             failure(status, "fmt.parse");
596             UDate dd = fmt.parse(tests[i+1], status);
597             failure(status, "fmt.parse");
598             UnicodeString s;
599             s = fmt.format(d, s);
600             UnicodeString ss;
601             ss = fmt.format(dd, ss);
602             if (d != dd)
603                 errln((UnicodeString) "Fail: " + d + " != " + dd);
604             if (s != ss)
605                 errln((UnicodeString)"Fail: " + s + " != " + ss);
606             logln("Ok: " + s + " " + d);
607         }
608 }
609 
610 /**
611  * @bug 4089106
612  */
Test4089106(void)613 void DateFormatRegressionTest::Test4089106(void)
614 {
615     TimeZone *def = TimeZone::createDefault();
616     //try {
617         TimeZone *z = new SimpleTimeZone((int)(1.25 * 3600000), "FAKEZONE");
618         TimeZone::setDefault(*z);
619         UErrorCode status = U_ZERO_ERROR;
620         SimpleDateFormat *f = new SimpleDateFormat(status);
621         if(U_FAILURE(status)) {
622           dataerrln("Couldn't create SimpleDateFormat, error %s", u_errorName(status));
623           delete f;
624           delete def;
625           delete z;
626           return;
627         }
628         failure(status, "new SimpleDateFormat");
629         if (f->getTimeZone()!= *z)
630             errln("Fail: SimpleTimeZone should use TimeZone.getDefault()");
631 
632         //}
633     //finally {
634         TimeZone::setDefault(*def);
635     //}
636 
637     delete z;
638     delete f;
639     delete def;
640 }
641 
642 /**
643  * @bug 4100302
644  */
645 
646 // {sfb} not applicable in C++??
647 
Test4100302(void)648 void DateFormatRegressionTest::Test4100302(void)
649 {
650 /*    Locale locales [] =  {
651         Locale::CANADA,
652         Locale::CANADA_FRENCH,
653         Locale::CHINA,
654         Locale::CHINESE,
655         Locale::ENGLISH,
656         Locale::FRANCE,
657         Locale::FRENCH,
658         Locale::GERMAN,
659         Locale::GERMANY,
660         Locale::ITALIAN,
661         Locale::ITALY,
662         Locale::JAPAN,
663         Locale::JAPANESE,
664         Locale::KOREA,
665         Locale::KOREAN,
666         Locale::PRC,
667         Locale::SIMPLIFIED_CHINESE,
668         Locale::TAIWAN,
669         Locale::TRADITIONAL_CHINESE,
670         Locale::UK,
671         Locale::US
672         };
673     //try {
674         UBool pass = TRUE;
675         for(int i = 0; i < 21; i++) {
676 
677             Format *format = DateFormat::createDateTimeInstance(DateFormat::FULL,
678                 DateFormat::FULL, locales[i]);
679             byte[] bytes;
680 
681             ByteArrayOutputStream baos = new ByteArrayOutputStream();
682             ObjectOutputStream oos = new ObjectOutputStream(baos);
683 
684             oos.writeObject(format);
685             oos.flush();
686 
687             baos.close();
688             bytes = baos.toByteArray();
689 
690             ObjectInputStream ois =
691                 new ObjectInputStream(new ByteArrayInputStream(bytes));
692 
693             if (!format.equals(ois.readObject())) {
694                 pass = FALSE;
695                 logln("DateFormat instance for locale " +
696                       locales[i] + " is incorrectly serialized/deserialized.");
697             } else {
698                 logln("DateFormat instance for locale " +
699                       locales[i] + " is OKAY.");
700             }
701         }
702         if (!pass) errln("Fail: DateFormat serialization/equality bug");
703     }
704     catch (IOException e) {
705         errln("Fail: " + e);
706         e.printStackTrace();
707     }
708     catch (ClassNotFoundException e) {
709         errln("Fail: " + e);
710         e.printStackTrace();
711     }
712 */}
713 
714 /**
715  * @bug 4101483
716  */
Test4101483(void)717 void DateFormatRegressionTest::Test4101483(void)
718 {
719     UErrorCode status = U_ZERO_ERROR;
720     SimpleDateFormat *sdf = new SimpleDateFormat(UnicodeString("z"), Locale::getUS(), status);
721     if (failure(status, "new SimpleDateFormat", TRUE)) return;
722     FieldPosition fp(UDAT_TIMEZONE_FIELD);
723     //Date d = date(9234567890L);
724     UDate d = 9234567890.0;
725     //StringBuffer buf = new StringBuffer("");
726     UnicodeString buf;
727     sdf->format(d, buf, fp);
728     //logln(sdf.format(d, buf, fp).toString());
729     logln(dateToString(d) + " => " + buf);
730     logln(UnicodeString("beginIndex = ") + fp.getBeginIndex());
731     logln(UnicodeString("endIndex = ") + fp.getEndIndex());
732     if (fp.getBeginIndex() == fp.getEndIndex())
733         errln("Fail: Empty field");
734 
735     delete sdf;
736 }
737 
738 /**
739  * @bug 4103340
740  * @bug 4138203
741  * This bug really only works in Locale.US, since that's what the locale
742  * used for Date.toString() is.  Bug 4138203 reports that it fails on Korean
743  * NT; it would actually have failed on any non-US locale.  Now it should
744  * work on all locales.
745  */
Test4103340(void)746 void DateFormatRegressionTest::Test4103340(void)
747 {
748     UErrorCode status = U_ZERO_ERROR;
749 
750     // choose a date that is the FIRST of some month
751     // and some arbitrary time
752     UDate d = date(97, 3, 1, 1, 1, 1);
753     SimpleDateFormat *df = new SimpleDateFormat(UnicodeString("MMMM"), Locale::getUS(), status);
754     if (failure(status, "new SimpleDateFormat", TRUE)) return;
755 
756     UnicodeString s;
757     s = dateToString(d, s);
758     UnicodeString s2;
759     FieldPosition pos(FieldPosition::DONT_CARE);
760     s2 = df->format(d, s2, pos);
761     logln("Date=" + s);
762     logln("DF=" + s2);
763     UnicodeString substr;
764     s2.extract(0,2, substr);
765     if (s.indexOf(substr) == -1)
766       errln("Months should match");
767 
768     delete df;
769 }
770 
771 /**
772  * @bug 4103341
773  */
Test4103341(void)774 void DateFormatRegressionTest::Test4103341(void)
775 {
776     TimeZone *saveZone  =TimeZone::createDefault();
777     //try {
778 
779     // {sfb} changed from setDefault to adoptDefault
780     TimeZone::adoptDefault(TimeZone::createTimeZone("CST"));
781     UErrorCode status = U_ZERO_ERROR;
782     SimpleDateFormat *simple = new SimpleDateFormat(UnicodeString("MM/dd/yyyy HH:mm"), status);
783     if(U_FAILURE(status)) {
784       dataerrln("Couldn't create SimpleDateFormat, error %s", u_errorName(status));
785       delete simple;
786       return;
787     }
788     failure(status, "new SimpleDateFormat");
789     TimeZone *temp = TimeZone::createDefault();
790     if(simple->getTimeZone() != *temp)
791             errln("Fail: SimpleDateFormat not using default zone");
792     //}
793     //finally {
794         TimeZone::adoptDefault(saveZone);
795     //}
796 
797     delete temp;
798     delete simple;
799 }
800 
801 /**
802  * @bug 4104136
803  */
Test4104136(void)804 void DateFormatRegressionTest::Test4104136(void)
805 {
806     UErrorCode status = U_ZERO_ERROR;
807     SimpleDateFormat *sdf = new SimpleDateFormat(status);
808     if(U_FAILURE(status)) {
809       dataerrln("Couldn't create SimpleDateFormat, error %s", u_errorName(status));
810       delete sdf;
811       return;
812     }
813     if(failure(status, "new SimpleDateFormat")) return;
814     UnicodeString pattern = "'time' hh:mm";
815     sdf->applyPattern(pattern);
816     logln("pattern: \"" + pattern + "\"");
817 
818     UnicodeString strings [] = {
819         (UnicodeString)"time 10:30",
820         (UnicodeString) "time 10:x",
821         (UnicodeString) "time 10x"
822     };
823 
824     ParsePosition ppos [] = {
825         ParsePosition(10),
826         ParsePosition(0),
827         ParsePosition(0)
828     };
829 
830     UDate dates [] = {
831         date(70, UCAL_JANUARY, 1, 10, 30),
832         -1,
833         -1
834     };
835 
836     /*Object[] DATA = {
837         "time 10:30", new ParsePosition(10), new Date(70, Calendar.JANUARY, 1, 10, 30),
838         "time 10:x", new ParsePosition(0), null,
839         "time 10x", new ParsePosition(0), null,
840     };*/
841 
842     for(int i = 0; i < 3; i++) {
843         UnicodeString text = strings[i];
844         ParsePosition finish = ppos[i];
845         UDate exp = dates[i];
846 
847         ParsePosition pos(0);
848         UDate d = sdf->parse(text, pos);
849         logln(" text: \"" + text + "\"");
850         logln(" index: %d", pos.getIndex());
851         logln((UnicodeString) " result: " + d);
852         if(pos.getIndex() != finish.getIndex())
853             errln(UnicodeString("Fail: Expected pos ") + finish.getIndex());
854         if (! ((d == 0 && exp == -1) || (d == exp)))
855             errln((UnicodeString) "Fail: Expected result " + exp);
856     }
857 
858     delete sdf;
859 }
860 
861 /**
862  * @bug 4104522
863  * CANNOT REPRODUCE
864  * According to the bug report, this test should throw a
865  * StringIndexOutOfBoundsException during the second parse.  However,
866  * this is not seen.
867  */
Test4104522(void)868 void DateFormatRegressionTest::Test4104522(void)
869 {
870     UErrorCode status = U_ZERO_ERROR;
871 
872     SimpleDateFormat *sdf = new SimpleDateFormat(status);
873     if(U_FAILURE(status)) {
874       dataerrln("Couldn't create SimpleDateFormat, error %s", u_errorName(status));
875       delete sdf;
876       return;
877     }
878     failure(status, "new SimpleDateFormat");
879     UnicodeString pattern = "'time' hh:mm";
880     sdf->applyPattern(pattern);
881     logln("pattern: \"" + pattern + "\"");
882 
883     // works correctly
884     ParsePosition pp(0);
885     UnicodeString text = "time ";
886     UDate dt = sdf->parse(text, pp);
887     logln(" text: \"" + text + "\"" +
888           " date: " + dt);
889 
890     // works wrong
891     pp.setIndex(0);
892     text = "time";
893     dt = sdf->parse(text, pp);
894     logln(" text: \"" + text + "\"" +
895           " date: " + dt);
896 
897     delete sdf;
898 }
899 
900 /**
901  * @bug 4106807
902  */
Test4106807(void)903 void DateFormatRegressionTest::Test4106807(void)
904 {
905     UDate dt;
906     DateFormat *df = DateFormat::createDateTimeInstance();
907 
908     UErrorCode status = U_ZERO_ERROR;
909     SimpleDateFormat *sdfs [] = {
910         new SimpleDateFormat(UnicodeString("yyyyMMddHHmmss"), status),
911         new SimpleDateFormat(UnicodeString("yyyyMMddHHmmss'Z'"), status),
912         new SimpleDateFormat(UnicodeString("yyyyMMddHHmmss''"), status),
913         new SimpleDateFormat(UnicodeString("yyyyMMddHHmmss'a''a'"), status),
914         new SimpleDateFormat(UnicodeString("yyyyMMddHHmmss %"), status)
915     };
916     if(U_FAILURE(status)) {
917       dataerrln("Couldn't create SimpleDateFormat, error %s", u_errorName(status));
918       delete sdfs[0];
919       delete sdfs[1];
920       delete sdfs[2];
921       delete sdfs[3];
922       delete sdfs[4];
923       return;
924     }
925 
926     failure(status, "new SimpleDateFormat");
927 
928     UnicodeString strings [] = {
929         (UnicodeString) "19980211140000",
930         (UnicodeString) "19980211140000",
931         (UnicodeString) "19980211140000",
932         (UnicodeString) "19980211140000a",
933         (UnicodeString) "19980211140000 "
934     };
935 
936     /*Object[] data = {
937         new SimpleDateFormat("yyyyMMddHHmmss"),       "19980211140000",
938         new SimpleDateFormat("yyyyMMddHHmmss'Z'"),    "19980211140000",
939         new SimpleDateFormat("yyyyMMddHHmmss''"),     "19980211140000",
940         new SimpleDateFormat("yyyyMMddHHmmss'a''a'"), "19980211140000a",
941         new SimpleDateFormat("yyyyMMddHHmmss %"),     "19980211140000 ",
942     };*/
943     GregorianCalendar *gc = new GregorianCalendar(status);
944     failure(status, "new GregorianCalendar");
945     TimeZone *timeZone = TimeZone::createDefault();
946 
947     TimeZone *gmt = timeZone->clone();
948 
949     gmt->setRawOffset(0);
950 
951     for(int32_t i = 0; i < 5; i++) {
952         SimpleDateFormat *format = sdfs[i];
953         UnicodeString dateString = strings[i];
954         //try {
955             format->setTimeZone(*gmt);
956             dt = format->parse(dateString, status);
957             // {sfb} some of these parses will fail purposely
958             if(U_FAILURE(status))
959                 break;
960             status = U_ZERO_ERROR;
961             UnicodeString fmtd;
962             FieldPosition pos(FieldPosition::DONT_CARE);
963             fmtd = df->format(dt, fmtd, pos);
964             logln(fmtd);
965             //logln(df->format(dt));
966             gc->setTime(dt, status);
967             failure(status, "gc->getTime");
968             logln(UnicodeString("") + gc->get(UCAL_ZONE_OFFSET, status));
969             failure(status, "gc->get");
970             UnicodeString s;
971             s = format->format(dt, s, pos);
972             logln(s);
973         /*}
974         catch (ParseException e) {
975             logln("No way Jose");
976         }*/
977     }
978 
979     delete timeZone;
980     delete df;
981     for(int32_t j = 0; j < 5; j++)
982         delete sdfs [j];
983      delete gc;
984     delete gmt;
985 }
986 
987 /*
988   Synopsis: Chinese time zone CTT is not recogonized correctly.
989   Description: Platform Chinese Windows 95 - ** Time zone set to CST **
990   */
991 /**
992  * @bug 4108407
993  */
994 
995 // {sfb} what to do with this one ??
Test4108407(void)996 void DateFormatRegressionTest::Test4108407(void)
997 {
998     /*long l = System.currentTimeMillis();
999     logln("user.timezone = " + System.getProperty("user.timezone", "?"));
1000     logln("Time Zone :" +
1001                        DateFormat.getDateInstance().getTimeZone().getID());
1002     logln("Default format :" +
1003                        DateFormat.getDateInstance().format(new Date(l)));
1004     logln("Full format :" +
1005                        DateFormat.getDateInstance(DateFormat.FULL).format(new
1006                                                                           Date(l)));
1007     logln("*** Set host TZ to CST ***");
1008     logln("*** THE RESULTS OF THIS TEST MUST BE VERIFIED MANUALLY ***");*/
1009 }
1010 
1011 /**
1012  * @bug 4134203
1013  * SimpleDateFormat won't parse "GMT"
1014  */
Test4134203(void)1015 void DateFormatRegressionTest::Test4134203(void)
1016 {
1017     UErrorCode status = U_ZERO_ERROR;
1018     UnicodeString dateFormat = "MM/dd/yy HH:mm:ss zzz";
1019     SimpleDateFormat *fmt = new SimpleDateFormat(dateFormat, status);
1020     if (failure(status, "new SimpleDateFormat", TRUE)) return;
1021     ParsePosition p0(0);
1022     UDate d = fmt->parse("01/22/92 04:52:00 GMT", p0);
1023     logln(dateToString(d));
1024     if(p0 == ParsePosition(0))
1025         errln("Fail: failed to parse 'GMT'");
1026     // In the failure case an exception is thrown by parse();
1027     // if no exception is thrown, the test passes.
1028 
1029     delete fmt;
1030 }
1031 
1032 /**
1033  * @bug 4151631
1034  * SimpleDateFormat incorrect handling of 2 single quotes in format()
1035  */
Test4151631(void)1036 void DateFormatRegressionTest::Test4151631(void)
1037 {
1038     UnicodeString pattern = "'TO_DATE('''dd'-'MM'-'yyyy HH:mm:ss''' , ''DD-MM-YYYY HH:MI:SS'')'";
1039     logln("pattern=" + pattern);
1040     UErrorCode status = U_ZERO_ERROR;
1041     SimpleDateFormat *format = new SimpleDateFormat(pattern, Locale::getUS(), status);
1042     if (failure(status, "new SimpleDateFormat", TRUE)) return;
1043     UnicodeString result;
1044     FieldPosition pos(FieldPosition::DONT_CARE);
1045     result = format->format(date(1998-1900, UCAL_JUNE, 30, 13, 30, 0), result, pos);
1046     if (result != "TO_DATE('30-06-1998 13:30:00' , 'DD-MM-YYYY HH:MI:SS')") {
1047         errln("Fail: result=" + result);
1048     }
1049     else {
1050         logln("Pass: result=" + result);
1051     }
1052 
1053     delete format;
1054 }
1055 
1056 /**
1057  * @bug 4151706
1058  * 'z' at end of date format throws index exception in SimpleDateFormat
1059  * CANNOT REPRODUCE THIS BUG ON 1.2FCS
1060  */
Test4151706(void)1061 void DateFormatRegressionTest::Test4151706(void)
1062 {
1063     UnicodeString dateString("Thursday, 31-Dec-98 23:00:00 GMT");
1064     UErrorCode status = U_ZERO_ERROR;
1065     SimpleDateFormat fmt(UnicodeString("EEEE, dd-MMM-yy HH:mm:ss z"), Locale::getUS(), status);
1066     if (failure(status, "new SimpleDateFormat", TRUE)) return;
1067     //try {
1068         UDate d = fmt.parse(dateString, status);
1069         failure(status, "fmt->parse");
1070        // {sfb} what about next two lines?
1071         //if (d.getTime() != Date.UTC(1998-1900, Calendar.DECEMBER, 31, 23, 0, 0))
1072         //    errln("Incorrect value: " + d);
1073     /*} catch (Exception e) {
1074         errln("Fail: " + e);
1075     }*/
1076     UnicodeString temp;
1077     FieldPosition pos(FieldPosition::DONT_CARE);
1078     logln(dateString + " -> " + fmt.format(d, temp, pos));
1079 }
1080 
1081 /**
1082  * @bug 4162071
1083  * Cannot reproduce this bug under 1.2 FCS -- it may be a convoluted duplicate
1084  * of some other bug that has been fixed.
1085  */
1086 void
Test4162071(void)1087 DateFormatRegressionTest::Test4162071(void)
1088 {
1089     UnicodeString dateString("Thu, 30-Jul-1999 11:51:14 GMT");
1090     UnicodeString format("EEE', 'dd-MMM-yyyy HH:mm:ss z"); // RFC 822/1123
1091     UErrorCode status = U_ZERO_ERROR;
1092     SimpleDateFormat df(format, Locale::getUS(), status);
1093     if(U_FAILURE(status)) {
1094         dataerrln("Couldn't create SimpleDateFormat - %s", u_errorName(status));
1095         return;
1096     }
1097 
1098     //try {
1099         UDate x = df.parse(dateString, status);
1100         if(U_SUCCESS(status))
1101             logln("Parse format \"" + format + "\" ok");
1102         else
1103             errln("Parse format \"" + format + "\" failed.");
1104         UnicodeString temp;
1105         FieldPosition pos(FieldPosition::DONT_CARE);
1106         logln(dateString + " -> " + df.format(x, temp, pos));
1107     //} catch (Exception e) {
1108     //    errln("Parse format \"" + format + "\" failed.");
1109     //}
1110 }
1111 
1112 /**
1113  * DateFormat shouldn't parse year "-1" as a two-digit year (e.g., "-1" -> 1999).
1114  */
Test4182066(void)1115 void DateFormatRegressionTest::Test4182066(void) {
1116     UErrorCode status = U_ZERO_ERROR;
1117     SimpleDateFormat fmt("MM/dd/yy", Locale::getUS(), status);
1118     SimpleDateFormat dispFmt("MMM dd yyyy GG", Locale::getUS(), status);
1119     if (U_FAILURE(status)) {
1120         dataerrln("Couldn't create SimpleDateFormat - %s", u_errorName(status));
1121         return;
1122     }
1123 
1124     /* We expect 2-digit year formats to put 2-digit years in the right
1125      * window.  Out of range years, that is, anything less than "00" or
1126      * greater than "99", are treated as literal years.  So "1/2/3456"
1127      * becomes 3456 AD.  Likewise, "1/2/-3" becomes -3 AD == 2 BC.
1128      */
1129     const char* STRINGS[] = {
1130         "02/29/00",
1131         "01/23/01",
1132         "04/05/-1",
1133         "01/23/-9",
1134         "11/12/1314",
1135         "10/31/1",
1136         "09/12/+1",
1137         "09/12/001",
1138     };
1139     int32_t STRINGS_COUNT = UPRV_LENGTHOF(STRINGS);
1140     UDate FAIL_DATE = (UDate) 0;
1141     UDate DATES[] = {
1142         date(2000-1900, UCAL_FEBRUARY, 29),
1143         date(2001-1900, UCAL_JANUARY,  23),
1144         date(  -1-1900, UCAL_APRIL,     5),
1145         date(  -9-1900, UCAL_JANUARY,  23),
1146         date(1314-1900, UCAL_NOVEMBER, 12),
1147         date(   1-1900, UCAL_OCTOBER,  31),
1148         FAIL_DATE, // "+1" isn't recognized by US NumberFormat
1149         date(   1-1900, UCAL_SEPTEMBER,12),
1150     };
1151 
1152     UnicodeString out;
1153     UBool pass = TRUE;
1154     for (int32_t i=0; i<STRINGS_COUNT; ++i) {
1155         UnicodeString str(STRINGS[i]);
1156         UDate expected = DATES[i];
1157         status = U_ZERO_ERROR;
1158         UDate actual = fmt.parse(str, status);
1159         if (U_FAILURE(status)) {
1160             actual = FAIL_DATE;
1161         }
1162         UnicodeString actStr;
1163         if (actual == FAIL_DATE) {
1164             actStr.append("null");
1165         } else {
1166             // Yuck: See j25
1167             ((DateFormat*)&dispFmt)->format(actual, actStr);
1168         }
1169 
1170         if (expected == actual) {
1171             out.append(str + " => " + actStr + "\n");
1172         } else {
1173             UnicodeString expStr;
1174             if (expected == FAIL_DATE) {
1175                 expStr.append("null");
1176             } else {
1177                 // Yuck: See j25
1178                 ((DateFormat*)&dispFmt)->format(expected, expStr);
1179             }
1180             out.append("FAIL: " + str + " => " + actStr
1181                        + ", expected " + expStr + "\n");
1182             pass = FALSE;
1183         }
1184     }
1185     if (pass) {
1186         log(out);
1187     } else {
1188         err(out);
1189     }
1190 }
1191 
1192 /**
1193  * j32 {JDK Bug 4210209 4209272}
1194  * DateFormat cannot parse Feb 29 2000 when setLenient(false)
1195  */
1196 void
Test4210209(void)1197 DateFormatRegressionTest::Test4210209(void) {
1198     UErrorCode status = U_ZERO_ERROR;
1199     UnicodeString pattern("MMM d, yyyy");
1200     SimpleDateFormat sfmt(pattern, Locale::getUS(), status);
1201     SimpleDateFormat sdisp("MMM dd yyyy GG", Locale::getUS(), status);
1202     DateFormat& fmt = *(DateFormat*)&sfmt; // Yuck: See j25
1203     DateFormat& disp = *(DateFormat*)&sdisp; // Yuck: See j25
1204     if (U_FAILURE(status)) {
1205         dataerrln("Couldn't create SimpleDateFormat - %s", u_errorName(status));
1206         return;
1207     }
1208     Calendar* calx = (Calendar*)fmt.getCalendar(); // cast away const!
1209     calx->setLenient(FALSE);
1210     UDate d = date(2000-1900, UCAL_FEBRUARY, 29);
1211     UnicodeString s, ss;
1212     fmt.format(d, s);
1213     logln(disp.format(d, ss.remove()) + " f> " + pattern +
1214           " => \"" + s + "\"");
1215     ParsePosition pos(0);
1216     d = fmt.parse(s, pos);
1217     logln(UnicodeString("\"") + s + "\" p> " + pattern +
1218           " => " + disp.format(d, ss.remove()));
1219     logln(UnicodeString("Parse pos = ") + pos.getIndex() +
1220           ", error pos = " + pos.getErrorIndex());
1221     if (pos.getErrorIndex() != -1) {
1222         errln(UnicodeString("FAIL: Error index should be -1"));
1223     }
1224 
1225     // The underlying bug is in GregorianCalendar.  If the following lines
1226     // succeed, the bug is fixed.  If the bug isn't fixed, they will throw
1227     // an exception.
1228     GregorianCalendar cal(status);
1229     if (U_FAILURE(status)) {
1230         errln("FAIL: Unable to create Calendar");
1231         return;
1232     }
1233     cal.clear();
1234     cal.setLenient(FALSE);
1235     cal.set(2000, UCAL_FEBRUARY, 29); // This should work!
1236     logln(UnicodeString("Attempt to set Calendar to Feb 29 2000: ") +
1237                         disp.format(cal.getTime(status), ss.remove()));
1238     if (U_FAILURE(status)) {
1239         errln("FAIL: Unable to set Calendar to Feb 29 2000");
1240     }
1241 }
1242 
Test714(void)1243 void DateFormatRegressionTest::Test714(void)
1244 {
1245     //try {
1246      UDate d(978103543000.);
1247     DateFormat *fmt = DateFormat::createDateTimeInstance(DateFormat::NONE,
1248                                                          DateFormat::MEDIUM,
1249                                                          Locale::getUS());
1250     if (fmt == NULL) {
1251         dataerrln("Error calling DateFormat::createDateTimeInstance");
1252         return;
1253     }
1254 
1255     UnicodeString s;
1256         UnicodeString tests =
1257           (UnicodeString) "7:25:43 AM" ;
1258         UErrorCode status = U_ZERO_ERROR;
1259         fmt->format (d,s);
1260         if(U_FAILURE(status))
1261           {
1262             errln((UnicodeString) "Fail, errmsg " + u_errorName(status));
1263             return;
1264           }
1265 
1266         if(s != tests)
1267         {
1268           errln((UnicodeString) "Fail: " + s + " != " + tests);
1269         }
1270         else
1271         {
1272           logln("OK: " + s + " == " + tests);
1273         }
1274 
1275    delete fmt;
1276 }
1277 
1278 class Test1684Data {
1279 public:
1280   int32_t year;
1281   int32_t month;
1282   int32_t date;
1283   int32_t womyear;
1284   int32_t wommon;
1285   int32_t wom;
1286   int32_t dow;
1287   UnicodeString data;
1288   UnicodeString normalized;
1289 
Test1684Data(int32_t xyear,int32_t xmonth,int32_t xdate,int32_t xwomyear,int32_t xwommon,int32_t xwom,int32_t xdow,const char * xdata,const char * xnormalized)1290   Test1684Data(int32_t xyear, int32_t xmonth, int32_t xdate,
1291                int32_t xwomyear, int32_t xwommon, int32_t xwom, int32_t xdow,
1292                const char *xdata, const char *xnormalized) :
1293     year(xyear),
1294     month(xmonth-1),
1295     date(xdate),
1296     womyear(xwomyear),
1297     wommon(xwommon-1),
1298     wom(xwom),
1299     dow(xdow),
1300     data(xdata,""),
1301     normalized((xnormalized==NULL)?xdata:xnormalized,"")
1302   { }
1303 };
1304 
Test1684(void)1305 void DateFormatRegressionTest::Test1684(void)
1306 {
1307   //      July 2001            August 2001           January 2002
1308   // Su Mo Tu We Th Fr Sa  Su Mo Tu We Th Fr Sa  Su Mo Tu We Th Fr Sa
1309   //  1  2  3  4  5  6  7            1  2  3  4         1  2  3  4  5
1310   //  8  9 10 11 12 13 14   5  6  7  8  9 10 11   6  7  8  9 10 11 12
1311   // 15 16 17 18 19 20 21  12 13 14 15 16 17 18  13 14 15 16 17 18 19
1312   // 22 23 24 25 26 27 28  19 20 21 22 23 24 25  20 21 22 23 24 25 26
1313   // 29 30 31              26 27 28 29 30 31     27 28 29 30 31
1314   Test1684Data *tests[] = {
1315     new Test1684Data(2001, 8,  6,  2001,8,2,UCAL_MONDAY,    "2001 08 02 Mon", NULL),
1316     new Test1684Data(2001, 8,  7,  2001,8,2,UCAL_TUESDAY,   "2001 08 02 Tue", NULL),
1317     new Test1684Data(2001, 8,  5,/*12,*/ 2001,8,2,UCAL_SUNDAY,    "2001 08 02 Sun", NULL),
1318     new Test1684Data(2001, 8,6, /*7,  30,*/ 2001,7,6,UCAL_MONDAY,    "2001 07 06 Mon", "2001 08 02 Mon"),
1319     new Test1684Data(2001, 8,7, /*7,  31,*/ 2001,7,6,UCAL_TUESDAY,   "2001 07 06 Tue", "2001 08 02 Tue"),
1320     new Test1684Data(2001, 8,  5,  2001,7,6,UCAL_SUNDAY,    "2001 07 06 Sun", "2001 08 02 Sun"),
1321     new Test1684Data(2001, 7,  30, 2001,8,1,UCAL_MONDAY,    "2001 08 01 Mon", "2001 07 05 Mon"),
1322     new Test1684Data(2001, 7,  31, 2001,8,1,UCAL_TUESDAY,   "2001 08 01 Tue", "2001 07 05 Tue"),
1323     new Test1684Data(2001, 7,29, /*8,  5,*/  2001,8,1,UCAL_SUNDAY,    "2001 08 01 Sun", "2001 07 05 Sun"),
1324     new Test1684Data(2001, 12, 31, 2001,12,6,UCAL_MONDAY,   "2001 12 06 Mon", NULL),
1325     new Test1684Data(2002, 1,  1,  2002,1,1,UCAL_TUESDAY,   "2002 01 01 Tue", NULL),
1326     new Test1684Data(2002, 1,  2,  2002,1,1,UCAL_WEDNESDAY, "2002 01 01 Wed", NULL),
1327     new Test1684Data(2002, 1,  3,  2002,1,1,UCAL_THURSDAY,  "2002 01 01 Thu", NULL),
1328     new Test1684Data(2002, 1,  4,  2002,1,1,UCAL_FRIDAY,    "2002 01 01 Fri", NULL),
1329     new Test1684Data(2002, 1,  5,  2002,1,1,UCAL_SATURDAY,  "2002 01 01 Sat", NULL),
1330     new Test1684Data(2001,12,30, /*2002, 1,  6,*/  2002,1,1,UCAL_SUNDAY,    "2002 01 01 Sun", "2001 12 06 Sun")
1331   };
1332 
1333 #define kTest1684Count  UPRV_LENGTHOF(tests)
1334 
1335   int32_t pass = 0, error = 0, warning = 0;
1336   int32_t i;
1337 
1338   UErrorCode status = U_ZERO_ERROR;
1339   UnicodeString pattern("yyyy MM WW EEE","");
1340   Calendar *cal = new GregorianCalendar(status);
1341   SimpleDateFormat *sdf = new SimpleDateFormat(pattern,status);
1342   if (U_FAILURE(status)) {
1343     dataerrln("Error constructing SimpleDateFormat");
1344     for(i=0;i<kTest1684Count;i++) {
1345         delete tests[i];
1346     }
1347     delete cal;
1348     delete sdf;
1349     return;
1350   }
1351   cal->setFirstDayOfWeek(UCAL_SUNDAY);
1352   cal->setMinimalDaysInFirstWeek(1);
1353 
1354   sdf->adoptCalendar(cal);
1355 
1356   cal = sdf->getCalendar()->clone(); // sdf may have deleted calendar
1357 
1358   if(!cal || !sdf || U_FAILURE(status)) {
1359     errln(UnicodeString("Error setting up test: ") + u_errorName(status));
1360   }
1361 
1362   for (i = 0; i < kTest1684Count; ++i) {
1363     Test1684Data &test = *(tests[i]);
1364     logln(UnicodeString("#") + i + UnicodeString("\n-----\nTesting round trip of ") + test.year +
1365         " " + (test.month + 1) +
1366         " " + test.date +
1367           " (written as) " + test.data);
1368 
1369     cal->clear();
1370     cal->set(test.year, test.month, test.date);
1371     UDate ms = cal->getTime(status);
1372 
1373     cal->clear();
1374     cal->set(UCAL_YEAR, test.womyear);
1375     cal->set(UCAL_MONTH, test.wommon);
1376     cal->set(UCAL_WEEK_OF_MONTH, test.wom);
1377     cal->set(UCAL_DAY_OF_WEEK, test.dow);
1378     UDate ms2 = cal->getTime(status);
1379 
1380     if (ms2 != ms) {
1381       errln((UnicodeString)"\nError: GregorianUCAL_DOM gave " + ms +
1382             "\n       GregorianUCAL_WOM gave " + ms2);
1383       error++;
1384     } else {
1385       pass++;
1386     }
1387 
1388     ms2 = sdf->parse(test.data, status);
1389     if(U_FAILURE(status)) {
1390       errln("parse exception: " + UnicodeString(u_errorName(status)));
1391     }
1392 
1393     if (ms2!=ms) {
1394       errln((UnicodeString)"\nError: GregorianCalendar gave      " + ms +
1395             "\n       SimpleDateFormat.parse gave " + ms2);
1396       error++;
1397     } else {
1398       pass++;
1399     }
1400 
1401     UnicodeString result;
1402     sdf->format(ms, result);
1403     if (result != test.normalized) {
1404       errln("\nWarning: format of '" + test.data + "' gave" +
1405             "\n                   '" + result + "'" +
1406             "\n          expected '" + test.normalized + "'");
1407       warning++;
1408     } else {
1409       pass++;
1410     }
1411 
1412     UDate ms3;
1413     ms3 = sdf->parse(result, status);
1414     if(U_FAILURE(status)) {
1415       errln("parse exception 2: " + (UnicodeString)u_errorName(status));
1416     }
1417 
1418     if (ms3!=ms) {
1419       error++;
1420       errln((UnicodeString)"\nError: Re-parse of '" + result + "' gave time of " +
1421           "\n        " + ms3 +
1422           "\n    not " + ms);
1423     } else {
1424       pass++;
1425             }
1426   }
1427 
1428   UnicodeString info
1429     = UnicodeString("Passed: ") + pass + ", Warnings: " + warning + ", Errors: " + error;
1430   if (error > 0) {
1431     errln(info);
1432   } else {
1433     logln(info);
1434   }
1435 
1436   for(i=0;i<kTest1684Count;i++) {
1437     delete tests[i];
1438   }
1439   delete cal;
1440   delete sdf;
1441 }
1442 
Test5554(void)1443 void DateFormatRegressionTest::Test5554(void)
1444 {
1445   UErrorCode status = U_ZERO_ERROR;
1446   UnicodeString pattern("Z","");
1447   UnicodeString newfoundland("Canada/Newfoundland", "");
1448   TimeZone *zone = TimeZone::createTimeZone(newfoundland);
1449   Calendar *cal = new GregorianCalendar(zone, status);
1450   SimpleDateFormat *sdf = new SimpleDateFormat(pattern,status);
1451   if (U_FAILURE(status)) {
1452     dataerrln("Error constructing SimpleDateFormat");
1453     delete cal;
1454     delete sdf;
1455     return;
1456   }
1457   cal->set(2007, 1, 14);
1458   UDate date = cal->getTime(status);
1459   if (U_FAILURE(status)) {
1460     errln("Error getting time to format");
1461     return;
1462   };
1463   sdf->adoptCalendar(cal);
1464   UnicodeString result;
1465   UnicodeString correct("-0330", "");
1466   sdf->format(date, result);
1467   if (result != correct) {
1468     errln("\nError: Newfoundland Z of Jan 14, 2007 gave '" + result + "', expected '" + correct + "'");
1469   }
1470   delete sdf;
1471 }
1472 
Test9237(void)1473 void DateFormatRegressionTest::Test9237(void)
1474 {
1475     UErrorCode status = U_ZERO_ERROR;
1476     UnicodeString pattern("VVVV");
1477 
1478     SimpleDateFormat fmt(pattern, status);  // default locale
1479     SimpleDateFormat fmtDE(pattern, Locale("de_DE"), status);
1480     if (U_FAILURE(status)) {
1481         dataerrln("Error constructing SimpleDateFormat");
1482         return;
1483     }
1484 
1485     // copy constructor
1486     SimpleDateFormat fmtCopyDE(fmtDE);
1487     UnicodeString resDE, resCopyDE;
1488 
1489     fmtDE.format(0.0, resDE);
1490     fmtCopyDE.format(0.0, resCopyDE);
1491 
1492     if (resDE != resCopyDE) {
1493         errln(UnicodeString("Error: different result by the copied instance - org:") + resDE + " copy:" + resCopyDE);
1494     }
1495 
1496     // test for assignment operator
1497     fmt = fmtDE;
1498 
1499     UnicodeString resAssigned;
1500     fmt.format(0.0, resAssigned);
1501 
1502     if (resDE != resAssigned) {
1503         errln(UnicodeString("Error: different results by the assigned instance - org:") + resDE + " assigned:" + resAssigned);
1504     }
1505 }
1506 
TestParsing(void)1507 void DateFormatRegressionTest::TestParsing(void) {
1508     UErrorCode status = U_ZERO_ERROR;
1509     UnicodeString pattern("EEE-WW-MMMM-yyyy");
1510     UnicodeString text("mon-02-march-2011");
1511     int32_t expectedDay = 7;
1512 
1513     SimpleDateFormat format(pattern, status);
1514     if (U_FAILURE(status)) {
1515         dataerrln("Unable to create SimpleDateFormat - %s", u_errorName(status));
1516         return;
1517     }
1518 
1519     Calendar *cal = new GregorianCalendar(status);
1520     if (cal == NULL || U_FAILURE(status)) {
1521         errln("Unable to create calendar - %s", u_errorName(status));
1522         return;
1523     }
1524 
1525     ParsePosition pos(0);
1526     format.parse(text, *cal, pos);
1527 
1528     if (cal->get(UCAL_DAY_OF_MONTH, status) != expectedDay) {
1529         errln("Parsing failed: day of month should be '7' with pattern: \"" + pattern + "\" for text: \"" + text + "\"");
1530     }
1531 
1532     delete cal;
1533 }
1534 
TestT10334(void)1535 void DateFormatRegressionTest::TestT10334(void) {
1536     UErrorCode status = U_ZERO_ERROR;
1537     UnicodeString pattern("'--: 'EEE-WW-MMMM-yyyy");
1538     UnicodeString text("--mon-02-march-2011");
1539     SimpleDateFormat format(pattern, status);
1540 
1541     logln("pattern["+pattern+"] text["+text+"]");
1542 
1543     if (U_FAILURE(status)) {
1544         dataerrln("Fail creating SimpleDateFormat object - %s", u_errorName(status));
1545         return;
1546     }
1547 
1548     format.setBooleanAttribute(UDAT_PARSE_PARTIAL_LITERAL_MATCH, FALSE, status);
1549     format.parse(text, status);
1550     if (!U_FAILURE(status)) {
1551         errln("parse partial match did NOT fail in strict mode - %s", u_errorName(status));
1552     }
1553 
1554     status = U_ZERO_ERROR;
1555     format.setBooleanAttribute(UDAT_PARSE_PARTIAL_LITERAL_MATCH, TRUE, status);
1556     format.parse(text, status);
1557     if (U_FAILURE(status)) {
1558         errln("parse partial match failure in lenient mode - %s", u_errorName(status));
1559     }
1560 
1561     status = U_ZERO_ERROR;
1562     pattern = UnicodeString("YYYY MM dd");
1563     text =    UnicodeString("2013 12 10");
1564     format.applyPattern(pattern);
1565     UDate referenceDate = format.parse(text, status);
1566 
1567     FieldPosition fp(FieldPosition::DONT_CARE);
1568     UnicodeString formattedString("");
1569     pattern = UnicodeString("YYYY LL dd ee cc qq QQ");
1570     format.applyPattern(pattern);
1571     format.format(referenceDate, formattedString, fp, status);
1572     logln("ref date: " + formattedString);
1573 
1574 
1575     char patternArray[] = "YYYY LLL dd eee ccc qqq QQQ";
1576     pattern = UnicodeString(patternArray);
1577     text = UnicodeString("2013 12 10 03 3 04 04");
1578     status = U_ZERO_ERROR;
1579     format.setBooleanAttribute(UDAT_PARSE_ALLOW_NUMERIC, TRUE, status);
1580     format.applyPattern(pattern);
1581     ParsePosition pp(0);
1582     format.parse(text, pp);
1583     if (pp.getErrorIndex() != -1) {
1584         errln("numeric parse error");
1585     }
1586 
1587     status = U_ZERO_ERROR;
1588     format.setBooleanAttribute(UDAT_PARSE_ALLOW_NUMERIC, FALSE, status);
1589     format.parse(text, status);
1590     if (!U_FAILURE(status)) {
1591         errln("numeric parse did NOT fail in strict mode", u_errorName(status));
1592     }
1593 
1594 }
1595 
1596 
1597 typedef struct {
1598     const char * locale;
1599     UBool leniency;
1600     UnicodeString parseString;
1601     UnicodeString pattern;
1602     UnicodeString expectedResult;       // null indicates expected error
1603 } TestDateFormatLeniencyItem;
1604 
1605 
TestT10619(void)1606 void DateFormatRegressionTest::TestT10619(void) {
1607     const UDate july022008 = 1215000001979.0;
1608     const TestDateFormatLeniencyItem items[] = {
1609         //locale    leniency    parse String                    pattern                             expected result
1610         { "en",     true,       UnicodeString("2008-07 02"),    UnicodeString("yyyy-LLLL dd"),      UnicodeString("2008-July 02") },
1611         { "en",     false,      UnicodeString("2008-07 03"),    UnicodeString("yyyy-LLLL dd"),      UnicodeString("") },
1612         { "en",     true,       UnicodeString("2008-Jan. 04"),  UnicodeString("yyyy-LLL dd"),       UnicodeString("2008-Jan 04") },
1613         { "en",     false,      UnicodeString("2008-Jan. 05"),  UnicodeString("yyyy-LLL dd"),       UnicodeString("") },
1614         { "en",     true,       UnicodeString("2008-Jan--06"),  UnicodeString("yyyy-MMM -- dd"),    UnicodeString("2008-Jan 06") },
1615         { "en",     false,      UnicodeString("2008-Jan--07"),  UnicodeString("yyyy-MMM -- dd"),    UnicodeString("") },
1616         { "en",     true,       UnicodeString("6 Jan 08 2008"), UnicodeString("eee MMM dd yyyy"),   UnicodeString("Sat Jan 08 2008") },
1617         { "en",     false,      UnicodeString("6 Jan 09 2008"), UnicodeString("eee MMM dd yyyy"),   UnicodeString("") },
1618         // terminator
1619         { NULL,     true,       UnicodeString(""),              UnicodeString(""),                  UnicodeString("") }
1620     };
1621     UErrorCode status = U_ZERO_ERROR;
1622     Calendar* cal = Calendar::createInstance(status);
1623     if (U_FAILURE(status)) {
1624         dataerrln(UnicodeString("FAIL: Unable to create Calendar for default timezone and locale."));
1625     } else {
1626         cal->setTime(july022008, status);
1627         const TestDateFormatLeniencyItem * itemPtr;
1628         for (itemPtr = items; itemPtr->locale != NULL; itemPtr++ ) {
1629 
1630             Locale locale = Locale::createFromName(itemPtr->locale);
1631             status = U_ZERO_ERROR;
1632             ParsePosition pos(0);
1633             SimpleDateFormat * sdmft = new SimpleDateFormat(itemPtr->pattern, locale, status);
1634             if (U_FAILURE(status)) {
1635                 dataerrln("Unable to create SimpleDateFormat - %s", u_errorName(status));
1636                 continue;
1637             }
1638             logln("parsing " + itemPtr->parseString);
1639             sdmft->setLenient(itemPtr->leniency);
1640             sdmft->setBooleanAttribute(UDAT_PARSE_ALLOW_WHITESPACE, itemPtr->leniency, status);
1641             sdmft->setBooleanAttribute(UDAT_PARSE_ALLOW_NUMERIC, itemPtr->leniency, status);
1642             sdmft->setBooleanAttribute(UDAT_PARSE_PARTIAL_LITERAL_MATCH, itemPtr->leniency, status);
1643             sdmft->parse(itemPtr->parseString, pos);
1644 
1645             delete sdmft;
1646             if(pos.getErrorIndex() > -1) {
1647                 if(itemPtr->expectedResult.length() != 0) {
1648                    errln("error: unexpected error - " + itemPtr->parseString + " - error index " + pos.getErrorIndex() +
1649                            " - leniency " + itemPtr->leniency);
1650                    continue;
1651                 } else {
1652                    continue;
1653                 }
1654             }
1655         }
1656     }
1657     delete cal;
1658 
1659 }
1660 
1661 
1662 typedef struct {
1663     UnicodeString text;
1664     UnicodeString pattern;
1665     int initialParsePos;
1666 } T10855Data;
1667 
TestT10855(void)1668 void DateFormatRegressionTest::TestT10855(void) {
1669     // NOTE: these should NOT parse
1670     const T10855Data items[] = {
1671         //parse String                          pattern                         initial parse pos
1672         { UnicodeString("September 30, 1998"),  UnicodeString("MM-dd-yyyy"),    0},
1673         { UnicodeString("123-73-1950"),         UnicodeString("MM-dd-yyyy"),    -1},
1674         { UnicodeString("12-23-1950"),          UnicodeString("MM-dd-yyyy"),    -1},
1675         // terminator
1676         { UnicodeString(""),                    UnicodeString(""),              0}
1677     };
1678     UErrorCode status = U_ZERO_ERROR;
1679 
1680     int x = 0;
1681     while(items[x].pattern.length() > 0)
1682     {
1683         status = U_ZERO_ERROR;
1684         logln("Date to parse: \""+items[x].text+"\"");
1685         logln("Starting Index: %d", items[x].initialParsePos);
1686 
1687         SimpleDateFormat dateFmt(items[x].pattern, status);
1688         if(U_FAILURE(status)) {
1689             errcheckln(status, "Failed dateFmt: %s", u_errorName(status));
1690             ++x;
1691             continue;
1692         }
1693         status = U_ZERO_ERROR;
1694 
1695         dateFmt.setLenient(false);
1696         dateFmt.setTimeZone(*TimeZone::getGMT());
1697 
1698         ParsePosition position(items[x].initialParsePos);
1699         logln("set position is now: %d", position.getIndex());
1700         UDate d = dateFmt.parse(items[x].text, position);
1701         if (position.getErrorIndex() != -1 || position.getIndex() == items[x].initialParsePos) {
1702             logln("Parse Failed. ErrorIndex is %d - Index is %d", position.getErrorIndex(), position.getIndex());
1703         } else {
1704             errln("Parse Succeeded...should have failed. Index is %d - ErrorIndex is %d", position.getIndex(), position.getErrorIndex());
1705         }
1706         logln("Parsed date returns %d\n", d);
1707 
1708         ++x;
1709     }
1710 }
1711 
TestT10906(void)1712 void DateFormatRegressionTest::TestT10906(void) {
1713 
1714       UErrorCode status = U_ZERO_ERROR;
1715       UnicodeString pattern = "MM-dd-yyyy";
1716       UnicodeString text = "06-10-2014";
1717       SimpleDateFormat format(pattern, status);
1718       int32_t errorIdx = 0;
1719       ParsePosition pp(-1);
1720       format.parse(text, pp);
1721       errorIdx = pp.getErrorIndex();
1722       if (errorIdx == -1) {
1723           errln("failed to report invalid (negative) starting parse position");
1724       }
1725 }
1726 
1727 #endif /* #if !UCONFIG_NO_FORMATTING */
1728 
1729 //eof
1730