1
/********************************************************************
3
* Copyright (c) 1997-2001, International Business Machines Corporation and
4
* others. All Rights Reserved.
5
********************************************************************/
8
#include "unicode/timezone.h"
9
#include "unicode/gregocal.h"
10
#include "unicode/smpdtfmt.h"
11
#include "unicode/datefmt.h"
12
#include "unicode/simpletz.h"
14
// *****************************************************************************
15
// class DateFormatTest
16
// *****************************************************************************
18
void DateFormatTest::runIndexedTest( int32_t index, UBool exec, const char* &name, char* /*par*/ )
20
// if (exec) logln((UnicodeString)"TestSuite DateFormatTest");
22
TESTCASE(0,TestEquals);
23
TESTCASE(1,TestTwoDigitYearDSTParse);
24
TESTCASE(2,TestFieldPosition);
25
TESTCASE(3,TestPartialParse994);
26
TESTCASE(4,TestRunTogetherPattern985);
27
TESTCASE(5,TestRunTogetherPattern917);
28
TESTCASE(6,TestCzechMonths459);
29
TESTCASE(7,TestLetterDPattern212);
30
TESTCASE(8,TestDayOfYearPattern195);
31
TESTCASE(9,TestQuotePattern161);
32
TESTCASE(10,TestBadInput135);
33
TESTCASE(11,TestBadInput135a);
34
TESTCASE(12,TestTwoDigitYear);
35
TESTCASE(13,TestDateFormatZone061);
36
TESTCASE(14,TestDateFormatZone146);
37
TESTCASE(15,TestLocaleDateFormat);
38
TESTCASE(16,TestWallyWedel);
39
TESTCASE(17,TestDateFormatCalendar);
40
default: name = ""; break;
44
// Test written by Wally Wedel and emailed to me.
45
void DateFormatTest::TestWallyWedel()
47
UErrorCode status = U_ZERO_ERROR;
49
* Instantiate a TimeZone so we can get the ids.
51
TimeZone *tz = new SimpleTimeZone(7,"");
53
* Computational variables.
55
int32_t offset, hours, minutes;
57
* Instantiate a SimpleDateFormat set up to produce a full time
60
SimpleDateFormat *sdf = new SimpleDateFormat((UnicodeString)"zzzz", status);
62
* A String array for the time zone ids.
65
const UnicodeString **ids = TimeZone::createAvailableIDs(ids_length);
67
* How many ids do we have?
69
logln("Time Zone IDs size: %d", ids_length);
71
* Column headings (sort of)
73
logln("Ordinal ID offset(h:m) name");
75
* Loop through the tzs.
77
UDate today = Calendar::getNow();
78
Calendar *cal = Calendar::createInstance(status);
79
for (int32_t i = 0; i < ids_length; i++) {
80
// logln(i + " " + ids[i]);
81
TimeZone *ttz = TimeZone::createTimeZone(*ids[i]);
82
// offset = ttz.getRawOffset();
83
cal->setTimeZone(*ttz);
84
cal->setTime(today, status);
85
offset = cal->get(Calendar::ZONE_OFFSET, status) + cal->get(Calendar::DST_OFFSET, status);
86
// logln(i + " " + ids[i] + " offset " + offset);
87
const char* sign = "+";
92
hours = offset/3600000;
93
minutes = (offset%3600000)/60000;
94
UnicodeString dstOffset = (UnicodeString)"" + sign + (hours < 10 ? "0" : "") +
95
(int32_t)hours + ":" + (minutes < 10 ? "0" : "") + (int32_t)minutes;
97
* Instantiate a date so we can display the time zone name.
99
sdf->setTimeZone(*ttz);
103
UnicodeString fmtOffset;
104
FieldPosition pos(0);
105
sdf->format(today,fmtOffset, pos);
106
// UnicodeString fmtOffset = tzS.toString();
107
UnicodeString *fmtDstOffset = 0;
108
if (fmtOffset.startsWith("GMT"))
110
//fmtDstOffset = fmtOffset->substring(3);
111
fmtDstOffset = new UnicodeString();
112
fmtOffset.extract(3, fmtOffset.length(), *fmtDstOffset);
117
UBool ok = fmtDstOffset == 0 || *fmtDstOffset == dstOffset;
120
logln(UnicodeString() + i + " " + *ids[i] + " " + dstOffset +
122
(fmtDstOffset != 0 ? " ok" : " ?"));
126
errln(UnicodeString() + i + " " + *ids[i] + " " + dstOffset +
127
" " + fmtOffset + " *** FAIL ***");
138
// -------------------------------------
144
DateFormatTest::TestEquals()
146
DateFormat* fmtA = DateFormat::createDateTimeInstance(DateFormat::MEDIUM, DateFormat::FULL);
147
DateFormat* fmtB = DateFormat::createDateTimeInstance(DateFormat::MEDIUM, DateFormat::FULL);
148
if (!(*fmtA == *fmtB)) errln((UnicodeString)"FAIL");
153
// -------------------------------------
156
* Test the parsing of 2-digit years.
159
DateFormatTest::TestTwoDigitYearDSTParse(void)
161
UErrorCode status = U_ZERO_ERROR;
162
SimpleDateFormat* fullFmt = new SimpleDateFormat((UnicodeString)"EEE MMM dd HH:mm:ss.SSS zzz yyyy G", status);
163
SimpleDateFormat *fmt = new SimpleDateFormat((UnicodeString)"dd-MMM-yy h:mm:ss 'o''clock' a z", Locale::getEnglish(), status);
164
//DateFormat* fmt = DateFormat::createDateTimeInstance(DateFormat::MEDIUM, DateFormat::FULL, Locale::ENGLISH);
165
UnicodeString* s = new UnicodeString("03-Apr-04 2:20:47 o'clock AM PST", "");
169
UDate d = fmt->parse(*s, status);
170
logln(*s + " P> " + ((DateFormat*)fullFmt)->format(d, str));
171
int32_t y, m, day, hr, min, sec;
172
dateToFields(d, y, m, day, hr, min, sec);
174
errln((UnicodeString)"FAIL: Should parse to hour " + hour);
176
if (U_FAILURE(status))
177
errln((UnicodeString)"FAIL: " + (int32_t)status);
184
// -------------------------------------
186
UChar toHexString(int32_t i) { return (UChar)(i + (i < 10 ? 0x30 : (0x41 - 10))); }
189
DateFormatTest::escape(UnicodeString& s)
192
for (int32_t i=0; i<s.length(); ++i)
194
UChar c = s[(int32_t)i];
195
if (c <= (UChar)0x7F) buf += c;
197
buf += (UChar)0x5c; buf += (UChar)0x55;
198
buf += toHexString((c & 0xF000) >> 12);
199
buf += toHexString((c & 0x0F00) >> 8);
200
buf += toHexString((c & 0x00F0) >> 4);
201
buf += toHexString(c & 0x000F);
207
const char* DateFormatTest::fieldNames[] = {
208
"ERA", "YEAR", "MONTH", "WEEK_OF_YEAR", "WEEK_OF_MONTH", "DAY_OF_MONTH",
209
"DAY_OF_YEAR", "DAY_OF_WEEK", "DAY_OF_WEEK_IN_MONTH", "AM_PM", "HOUR",
210
"HOUR_OF_DAY", "MINUTE", "SECOND", "MILLISECOND", "ZONE_OFFSET", //"DST_OFFSET",
211
"YEAR_WOY", "DOW_LOCAL"
214
// -------------------------------------
216
// Map Calendar field number to to DateFormat field number
217
const DateFormat::EField
218
DateFormatTest::fgCalendarToDateFormatField[] = {
219
DateFormat::kEraField,
220
DateFormat::kYearField,
221
DateFormat::kMonthField,
222
DateFormat::kWeekOfYearField,
223
DateFormat::kWeekOfMonthField,
224
DateFormat::kDateField,
225
DateFormat::kDayOfYearField,
226
DateFormat::kDayOfWeekField,
227
DateFormat::kDayOfWeekInMonthField,
228
DateFormat::kAmPmField,
229
DateFormat::kHour1Field,
230
DateFormat::kHourOfDay0Field,
231
DateFormat::kMinuteField,
232
DateFormat::kSecondField,
233
DateFormat::kMillisecondField,
234
DateFormat::kTimezoneField,
235
DateFormat::kYearWOYField,
236
DateFormat::kDOWLocalField,
237
(DateFormat::EField) -1
241
* Verify that returned field position indices are correct.
244
DateFormatTest::TestFieldPosition(void)
246
UErrorCode status = U_ZERO_ERROR;
247
DateFormat* dateFormats[4];
248
int32_t dateFormats_length = (int32_t)(sizeof(dateFormats) / sizeof(dateFormats[0]));
250
/* {sfb} This test was coded incorrectly.
251
/ FieldPosition uses the fields in the class you are formatting with
252
/ So, for example, to get the DATE field from a DateFormat use
253
/ DateFormat::DATE_FIELD, __not__ Calendar::DATE
254
/ The ordering of the expected values used previously was wrong.
255
/ instead of re-ordering this mess of strings, just transform the index values */
257
/* field values, in Calendar order */
259
const char* expected[] = {
260
"", "1997", "August", "", "", "13", "", "Wednesday", "", "PM", "2", "",
261
"34", "12", "", "PDT", "",
262
/* Following two added by weiv for two new fields */ "", "",
263
"", "1997", "#",/* # is a marker for "ao\xfbt" == "aou^t" */ "", "", "13", "", "mercredi",
264
"", "", "", "14", "34", "", "", "GMT-07:00", "",
265
/* Following two added by weiv for two new fields */ "", "",
266
"AD", "97", "8", "33", "3", "13", "225", "Wed", "2", "PM", "2",
267
"14", "34", "12", "5", "PDT",
268
/* Following two added by weiv for two new fields */ "97", "4", "",
269
"AD", "1997", "August", "0033",
270
"0003", "0013", "0225", "Wednesday", "0002", "PM", "0002", "0014",
271
"0034", "0012", "513", "Pacific Daylight Time",
272
/* Following two added by weiv for two new fields */ "1997", "0004",
277
UDate someDate = 871508052513.0;
280
dateFormats[0] = DateFormat::createDateTimeInstance(DateFormat::FULL, DateFormat::FULL, Locale::getUS());
281
dateFormats[1] = DateFormat::createDateTimeInstance(DateFormat::FULL, DateFormat::FULL, Locale::getFrance());
282
dateFormats[2] = new SimpleDateFormat((UnicodeString)"G, y, M, d, k, H, m, s, S, E, D, F, w, W, a, h, K, z, Y, e", status);
283
dateFormats[3] = new SimpleDateFormat((UnicodeString)"GGGG, yyyy, MMMM, dddd, kkkk, HHHH, mmmm, ssss, SSSS, EEEE, DDDD, FFFF, wwww, WWWW, aaaa, hhhh, KKKK, zzzz, YYYY, eeee", status);
284
for (j = 0, exp = 0; j < dateFormats_length;++j) {
286
DateFormat* df = dateFormats[j];
287
logln((UnicodeString)" Pattern = " + ((SimpleDateFormat*)df)->toPattern(str));
289
logln((UnicodeString)" Result = " + df->format(someDate, str));
290
for (int32_t i = 0; i < Calendar::FIELD_COUNT;++i) {
292
getFieldText(df, i, someDate, field);
293
UnicodeString expStr;
294
if(expected[exp][0]!='#') {
295
expStr=UnicodeString(expected[exp]);
297
/* we cannot have latin-1 characters in source code, therefore we fix up the string for "aou^t" */
298
expStr.append((UChar)0x61).append((UChar)0x6f).append((UChar32)0xfb).append((UChar)0x74);
301
if (!(field == expStr)) errln(UnicodeString("FAIL: field #") + i + " " +
302
fieldNames[i] + " = \"" + escape(field) + "\", expected \"" + escape(expStr) + "\"");
306
for (j=0; j<dateFormats_length; ++j) delete dateFormats[j];
307
if (U_FAILURE(status)) errln((UnicodeString)"FAIL: UErrorCode received during test: " + (int32_t)status);
310
// -------------------------------------
313
DateFormatTest::getFieldText(DateFormat* df, int32_t field, UDate date, UnicodeString& str)
315
UnicodeString formatResult;
316
// {sfb} added to convert Calendar Fields to DateFormat fields
317
FieldPosition pos(fgCalendarToDateFormatField[field]);
318
df->format(date, formatResult, pos);
319
//formatResult.extract(pos.getBeginIndex(), pos.getEndIndex(), str);
320
formatResult.extractBetween(pos.getBeginIndex(), pos.getEndIndex(), str);
323
// -------------------------------------
326
* Verify that strings which contain incomplete specifications are parsed
327
* correctly. In some instances, this means not being parsed at all, and
328
* returning an appropriate error.
331
DateFormatTest::TestPartialParse994()
333
UErrorCode status = U_ZERO_ERROR;
334
SimpleDateFormat* f = new SimpleDateFormat(status);
336
tryPat994(f, "yy/MM/dd HH:mm:ss", "97/01/17 10:11:42", date(97, 1 - 1, 17, 10, 11, 42));
337
tryPat994(f, "yy/MM/dd HH:mm:ss", "97/01/17 10:", null);
338
tryPat994(f, "yy/MM/dd HH:mm:ss", "97/01/17 10", null);
339
tryPat994(f, "yy/MM/dd HH:mm:ss", "97/01/17 ", null);
340
tryPat994(f, "yy/MM/dd HH:mm:ss", "97/01/17", null);
341
if (U_FAILURE(status)) errln((UnicodeString)"FAIL: UErrorCode received during test: " + (int32_t)status);
345
// -------------------------------------
348
DateFormatTest::tryPat994(SimpleDateFormat* format, const char* pat, const char* str, UDate expected)
350
UErrorCode status = U_ZERO_ERROR;
352
logln(UnicodeString("Pattern \"") + pat + "\" String \"" + str + "\"");
354
format->applyPattern(pat);
355
UDate date = format->parse(str, status);
356
if (U_FAILURE(status) || date == null)
358
logln((UnicodeString)"ParseException: " + (int32_t)status);
359
if (expected != null) errln((UnicodeString)"FAIL: Expected " + dateToString(expected));
364
((DateFormat*)format)->format(date, f);
365
logln(UnicodeString(" parse(") + str + ") -> " + dateToString(date));
366
logln((UnicodeString)" format -> " + f);
367
if (expected == null ||
368
!(date == expected)) errln((UnicodeString)"FAIL: Expected null");//" + expected);
369
if (!(f == str)) errln(UnicodeString("FAIL: Expected ") + str);
372
//catch(ParseException e) {
373
// logln((UnicodeString)"ParseException: " + e.getMessage());
374
// if (expected != null) errln((UnicodeString)"FAIL: Expected " + dateToString(expected));
376
//catch(Exception e) {
377
// errln((UnicodeString)"*** Exception:");
378
// e.printStackTrace();
382
// -------------------------------------
385
* Verify the behavior of patterns in which digits for different fields run together
386
* without intervening separators.
389
DateFormatTest::TestRunTogetherPattern985()
391
UErrorCode status = U_ZERO_ERROR;
392
UnicodeString format("yyyyMMddHHmmssSSS");
393
UnicodeString now, then;
395
SimpleDateFormat *formatter = new SimpleDateFormat(format, status);
396
UDate date1 = Calendar::getNow();
397
((DateFormat*)formatter)->format(date1, now);
399
ParsePosition pos(0);
400
UDate date2 = formatter->parse(now, pos);
401
if (date2 == 0) then = "Parse stopped at " + pos.getIndex();
402
else ((DateFormat*)formatter)->format(date2, then);
404
if (!(date2 == date1)) errln((UnicodeString)"FAIL");
406
if (U_FAILURE(status)) errln((UnicodeString)"FAIL: UErrorCode received during test: " + (int32_t)status);
409
// -------------------------------------
412
* Verify the behavior of patterns in which digits for different fields run together
413
* without intervening separators.
416
DateFormatTest::TestRunTogetherPattern917()
418
UErrorCode status = U_ZERO_ERROR;
419
SimpleDateFormat* fmt;
420
UnicodeString myDate;
421
fmt = new SimpleDateFormat((UnicodeString)"yyyy/MM/dd", status);
422
myDate = "1997/02/03";
423
testIt917(fmt, myDate, date(97, 2 - 1, 3));
425
fmt = new SimpleDateFormat((UnicodeString)"yyyyMMdd", status);
427
testIt917(fmt, myDate, date(97, 3 - 1, 4));
429
if (U_FAILURE(status)) errln((UnicodeString)"FAIL: UErrorCode received during test: " + (int32_t)status);
432
// -------------------------------------
435
DateFormatTest::testIt917(SimpleDateFormat* fmt, UnicodeString& str, UDate expected)
437
UErrorCode status = U_ZERO_ERROR;
438
UnicodeString pattern;
439
logln((UnicodeString)"pattern=" + fmt->toPattern(pattern) + " string=" + str);
442
((Format*)fmt)->parseObject(str, o, status);
444
if (U_FAILURE(status)) return;
445
//catch(ParseException e) {
446
// e.printStackTrace();
449
logln((UnicodeString)"Parsed object: " + dateToString(o.getDate()));
450
if (!(o.getDate() == expected)) errln((UnicodeString)"FAIL: Expected " + dateToString(expected));
451
UnicodeString formatted; ((Format*)fmt)->format(o, formatted, status);
452
logln((UnicodeString)"Formatted string: " + formatted);
453
if (!(formatted == str)) errln((UnicodeString)"FAIL: Expected " + str);
454
if (U_FAILURE(status)) errln((UnicodeString)"FAIL: UErrorCode received during test: " + (int32_t)status);
457
// -------------------------------------
460
* Verify the handling of Czech June and July, which have the unique attribute that
461
* one is a proper prefix substring of the other.
464
DateFormatTest::TestCzechMonths459()
466
UErrorCode status = U_ZERO_ERROR;
467
DateFormat* fmt = DateFormat::createDateInstance(DateFormat::FULL, Locale("cs", "", ""));
468
UnicodeString pattern;
469
logln((UnicodeString)"Pattern " + ((SimpleDateFormat*) fmt)->toPattern(pattern));
470
UDate june = date(97, Calendar::JUNE, 15);
471
UDate july = date(97, Calendar::JULY, 15);
472
UnicodeString juneStr; fmt->format(june, juneStr);
473
UnicodeString julyStr; fmt->format(july, julyStr);
475
logln((UnicodeString)"format(June 15 1997) = " + juneStr);
476
UDate d = fmt->parse(juneStr, status);
477
UnicodeString s; fmt->format(d, s);
478
int32_t month,yr,day,hr,min,sec; dateToFields(d,yr,month,day,hr,min,sec);
479
logln((UnicodeString)" -> parse -> " + s + " (month = " + month + ")");
480
if (month != Calendar::JUNE) errln((UnicodeString)"FAIL: Month should be June");
481
logln((UnicodeString)"format(July 15 1997) = " + julyStr);
482
d = fmt->parse(julyStr, status);
484
dateToFields(d,yr,month,day,hr,min,sec);
485
logln((UnicodeString)" -> parse -> " + s + " (month = " + month + ")");
486
if (month != Calendar::JULY) errln((UnicodeString)"FAIL: Month should be July");
488
//catch(ParseException e) {
489
if (U_FAILURE(status))
490
errln((UnicodeString)"Exception: " + (int32_t)status);
495
// -------------------------------------
498
* Test the handling of 'D' in patterns.
501
DateFormatTest::TestLetterDPattern212()
503
UErrorCode status = U_ZERO_ERROR;
504
UnicodeString dateString("1995-040.05:01:29");
505
UnicodeString bigD("yyyy-DDD.hh:mm:ss");
506
UnicodeString littleD("yyyy-ddd.hh:mm:ss");
507
UDate expLittleD = date(95, 0, 1, 5, 1, 29);
508
UDate expBigD = expLittleD + 39 * 24 * 3600000.0;
509
expLittleD = expBigD; // Expect the same, with default lenient parsing
510
logln((UnicodeString)"dateString= " + dateString);
511
SimpleDateFormat *formatter = new SimpleDateFormat(bigD, status);
512
ParsePosition pos(0);
513
UDate myDate = formatter->parse(dateString, pos);
514
logln((UnicodeString)"Using " + bigD + " -> " + myDate);
515
if (myDate != expBigD) errln((UnicodeString)"FAIL: Expected " + dateToString(expBigD));
517
formatter = new SimpleDateFormat(littleD, status);
518
pos = ParsePosition(0);
519
myDate = formatter->parse(dateString, pos);
520
logln((UnicodeString)"Using " + littleD + " -> " + dateToString(myDate));
521
if (myDate != expLittleD) errln((UnicodeString)"FAIL: Expected " + dateToString(expLittleD));
523
if (U_FAILURE(status)) errln((UnicodeString)"FAIL: UErrorCode received during test: " + (int32_t)status);
526
// -------------------------------------
529
* Test the day of year pattern.
532
DateFormatTest::TestDayOfYearPattern195()
534
UErrorCode status = U_ZERO_ERROR;
535
UDate today = Calendar::getNow();
536
int32_t year,month,day,hour,min,sec; dateToFields(today,year,month,day,hour,min,sec);
537
UDate expected = date(year, month, day);
538
logln((UnicodeString)"Test Date: " + dateToString(today));
539
SimpleDateFormat* sdf = (SimpleDateFormat*)DateFormat::createDateInstance();
540
tryPattern(*sdf, today, 0, expected);
541
tryPattern(*sdf, today, "G yyyy DDD", expected);
543
if (U_FAILURE(status)) errln((UnicodeString)"FAIL: UErrorCode received during test: " + (int32_t)status);
546
// -------------------------------------
549
DateFormatTest::tryPattern(SimpleDateFormat& sdf, UDate d, const char* pattern, UDate expected)
551
UErrorCode status = U_ZERO_ERROR;
552
if (pattern != 0) sdf.applyPattern(pattern);
553
UnicodeString thePat;
554
logln((UnicodeString)"pattern: " + sdf.toPattern(thePat));
555
UnicodeString formatResult; (*(DateFormat*)&sdf).format(d, formatResult);
556
logln((UnicodeString)" format -> " + formatResult);
558
UDate d2 = sdf.parse(formatResult, status);
559
logln((UnicodeString)" parse(" + formatResult + ") -> " + dateToString(d2));
560
if (d2 != expected) errln((UnicodeString)"FAIL: Expected " + dateToString(expected));
561
UnicodeString format2; (*(DateFormat*)&sdf).format(d2, format2);
562
logln((UnicodeString)" format -> " + format2);
563
if (!(formatResult == format2)) errln((UnicodeString)"FAIL: Round trip drift");
565
//catch(Exception e) {
566
if (U_FAILURE(status))
567
errln((UnicodeString)"Error: " + (int32_t)status);
571
// -------------------------------------
574
* Test the handling of single quotes in patterns.
577
DateFormatTest::TestQuotePattern161()
579
UErrorCode status = U_ZERO_ERROR;
580
SimpleDateFormat* formatter = new SimpleDateFormat((UnicodeString)"MM/dd/yyyy 'at' hh:mm:ss a zzz", status);
581
UDate currentTime_1 = date(97, Calendar::AUGUST, 13, 10, 42, 28);
582
UnicodeString dateString; ((DateFormat*)formatter)->format(currentTime_1, dateString);
583
UnicodeString exp("08/13/1997 at 10:42:28 AM ");
584
logln((UnicodeString)"format(" + dateToString(currentTime_1) + ") = " + dateString);
585
if (0 != dateString.compareBetween(0, exp.length(), exp, 0, exp.length())) errln((UnicodeString)"FAIL: Expected " + exp);
587
if (U_FAILURE(status)) errln((UnicodeString)"FAIL: UErrorCode received during test: " + (int32_t)status);
590
// -------------------------------------
593
* Verify the correct behavior when handling invalid input strings.
596
DateFormatTest::TestBadInput135()
598
UErrorCode status = U_ZERO_ERROR;
599
DateFormat::EStyle looks[] = {
600
DateFormat::SHORT, DateFormat::MEDIUM, DateFormat::LONG, DateFormat::FULL
602
int32_t looks_length = (int32_t)(sizeof(looks) / sizeof(looks[0]));
603
const char* strings[] = {
604
"Mar 15", "Mar 15 1997", "asdf", "3/1/97 1:23:", "3/1/00 1:23:45 AM"
606
int32_t strings_length = (int32_t)(sizeof(strings) / sizeof(strings[0]));
607
DateFormat *full = DateFormat::createDateTimeInstance(DateFormat::LONG, DateFormat::LONG);
608
UnicodeString expected("March 1, 2000 1:23:45 AM ");
609
for (int32_t i = 0; i < strings_length;++i) {
610
const char* text = strings[i];
611
for (int32_t j = 0; j < looks_length;++j) {
612
DateFormat::EStyle dateLook = looks[j];
613
for (int32_t k = 0; k < looks_length;++k) {
614
DateFormat::EStyle timeLook = looks[k];
615
DateFormat *df = DateFormat::createDateTimeInstance(dateLook, timeLook);
616
UnicodeString prefix = UnicodeString(text) + ", " + dateLook + "/" + timeLook + ": ";
618
UDate when = df->parse(text, status);
619
if (when == 0 && U_SUCCESS(status)) {
620
errln(prefix + "SHOULD NOT HAPPEN: parse returned 0.");
623
if (U_SUCCESS(status))
625
UnicodeString format;
626
full->format(when, format);
627
logln(prefix + "OK: " + format);
628
if (0!=format.compareBetween(0, expected.length(), expected, 0, expected.length()))
629
errln((UnicodeString)"FAIL: Expected " + expected + " got " + format);
632
//catch(ParseException e) {
634
status = U_ZERO_ERROR;
636
//catch(StringIndexOutOfBoundsException e) {
637
// errln(prefix + "SHOULD NOT HAPPEN: " + (int)status);
644
if (U_FAILURE(status))
645
errln((UnicodeString)"FAIL: UErrorCode received during test: " + (int32_t)status);
648
const char* DateFormatTest::parseFormats[] = {
657
"h:mm a MMMM d, yyyy"
660
const char* DateFormatTest::inputStrings[] = {
661
"bogus string", 0, 0, 0, 0, 0, 0, 0, 0, 0,
662
"April 1, 1997", "April 1, 1997", 0, 0, 0, 0, 0, "April 1", 0, 0,
663
"Jan 1, 1970", "January 1, 1970", 0, 0, 0, 0, 0, "January 1", 0, 0,
664
"Jan 1 2037", 0, "January 1 2037", 0, 0, 0, 0, "January 1", 0, 0,
665
"1/1/70", 0, 0, "1/1/70", 0, 0, 0, 0, "0001", 0,
666
"5 May 1997", 0, 0, 0, 0, "5 May 1997", "5 May", 0, "0005", 0,
667
"16 May", 0, 0, 0, 0, 0, "16 May", 0, "0016", 0,
668
"April 30", 0, 0, 0, 0, 0, 0, "April 30", 0, 0,
669
"1998", 0, 0, 0, 0, 0, 0, 0, "1998", 0,
670
"1", 0, 0, 0, 0, 0, 0, 0, "0001", 0,
671
"3:00 pm Jan 1, 1997", 0, 0, 0, 0, 0, 0, 0, "0003", "3:00 PM January 1, 1997",
674
// -------------------------------------
677
* Verify the correct behavior when parsing an array of inputs against an
678
* array of patterns, with known results. The results are encoded after
679
* the input strings in each row.
682
DateFormatTest::TestBadInput135a()
684
UErrorCode status = U_ZERO_ERROR;
685
SimpleDateFormat* dateParse = new SimpleDateFormat(status);
688
const uint32_t PF_LENGTH = (int32_t)(sizeof(parseFormats)/sizeof(parseFormats[0]));
689
const uint32_t INPUT_LENGTH = (int32_t)(sizeof(inputStrings)/sizeof(inputStrings[0]));
691
dateParse->applyPattern("d MMMM, yyyy");
692
dateParse->adoptTimeZone(TimeZone::createDefault());
694
UnicodeString thePat;
695
logln(UnicodeString("Trying to parse \"") + s + "\" with " + dateParse->toPattern(thePat));
697
date = dateParse->parse(s, status);
698
if (U_SUCCESS(status))
699
errln((UnicodeString)"FAIL: Expected exception during parse");
701
//catch(Exception ex) {
703
logln((UnicodeString)"Exception during parse: " + (int32_t)status);
704
status = U_ZERO_ERROR;
706
for (uint32_t i = 0; i < INPUT_LENGTH; i += (PF_LENGTH + 1)) {
707
ParsePosition parsePosition(0);
708
UnicodeString s( inputStrings[i]);
709
for (uint32_t index = 0; index < PF_LENGTH;++index) {
710
const char* expected = inputStrings[i + 1 + index];
711
dateParse->applyPattern(parseFormats[index]);
712
dateParse->adoptTimeZone(TimeZone::createDefault());
714
parsePosition.setIndex(0);
715
date = dateParse->parse(s, parsePosition);
716
if (parsePosition.getIndex() != 0) {
717
UnicodeString s1, s2;
718
s.extract(0, parsePosition.getIndex(), s1);
719
s.extract(parsePosition.getIndex(), s.length(), s2);
721
errln((UnicodeString)"ERROR: null result fmt=\"" +
722
parseFormats[index] +
723
"\" pos=" + parsePosition.getIndex() + " " +
727
UnicodeString result;
728
((DateFormat*)dateParse)->format(date, result);
729
logln((UnicodeString)"Parsed \"" + s + "\" using \"" + dateParse->toPattern(thePat) + "\" to: " + result);
731
errln((UnicodeString)"FAIL: Expected parse failure");
732
else if (!(result == expected))
733
errln(UnicodeString("FAIL: Expected ") + expected);
736
else if (expected != 0) {
737
errln(UnicodeString("FAIL: Expected ") + expected + " from \"" +
738
s + "\" with \"" + dateParse->toPattern(thePat) + "\"");
741
//catch(Exception ex) {
742
if (U_FAILURE(status))
743
errln((UnicodeString)"An exception was thrown during parse: " + (int32_t)status);
748
if (U_FAILURE(status))
749
errln((UnicodeString)"FAIL: UErrorCode received during test: " + (int32_t)status);
752
// -------------------------------------
755
* Test the parsing of two-digit years.
758
DateFormatTest::TestTwoDigitYear()
760
DateFormat* fmt = DateFormat::createDateInstance(DateFormat::SHORT, Locale::getUK());
761
parse2DigitYear(*fmt, "5/6/17", date(117, Calendar::JUNE, 5));
762
parse2DigitYear(*fmt, "4/6/34", date(34, Calendar::JUNE, 4));
766
// -------------------------------------
769
DateFormatTest::parse2DigitYear(DateFormat& fmt, const char* str, UDate expected)
771
UErrorCode status = U_ZERO_ERROR;
773
UDate d = fmt.parse(str, status);
774
UnicodeString thePat;
775
logln(UnicodeString("Parsing \"") + str + "\" with " + ((SimpleDateFormat*)&fmt)->toPattern(thePat) +
776
" => " + dateToString(d));
777
if (d != expected) errln((UnicodeString)"FAIL: Expected " + expected);
779
//catch(ParseException e) {
780
if (U_FAILURE(status))
781
errln((UnicodeString)"FAIL: Got exception");
785
// -------------------------------------
788
* Test the formatting of time zones.
791
DateFormatTest::TestDateFormatZone061()
793
UErrorCode status = U_ZERO_ERROR;
795
DateFormat *formatter;
796
date= 859248000000.0;
797
logln((UnicodeString)"Date 1997/3/25 00:00 GMT: " + date);
798
formatter = new SimpleDateFormat((UnicodeString)"dd-MMM-yyyyy HH:mm", Locale::getUK(), status);
799
formatter->adoptTimeZone(TimeZone::createTimeZone("GMT"));
800
UnicodeString temp; formatter->format(date, temp);
801
logln((UnicodeString)"Formatted in GMT to: " + temp);
803
UDate tempDate = formatter->parse(temp, status);
804
logln((UnicodeString)"Parsed to: " + dateToString(tempDate));
805
if (tempDate != date) errln((UnicodeString)"FAIL: Expected " + dateToString(date));
807
//catch(Throwable t) {
808
if (U_FAILURE(status))
809
errln((UnicodeString)"Date Formatter throws: " + (int32_t)status);
814
// -------------------------------------
817
* Test the formatting of time zones.
820
DateFormatTest::TestDateFormatZone146()
822
TimeZone *saveDefault = TimeZone::createDefault();
825
TimeZone *thedefault = TimeZone::createTimeZone("GMT");
826
TimeZone::setDefault(*thedefault);
827
// java.util.Locale.setDefault(new java.util.Locale("ar", "", ""));
829
// check to be sure... its GMT all right
830
TimeZone *testdefault = TimeZone::createDefault();
831
UnicodeString testtimezone;
832
testdefault->getID(testtimezone);
833
if (testtimezone == "GMT")
834
logln("Test timezone = " + testtimezone);
836
errln("Test timezone should be GMT, not " + testtimezone);
838
UErrorCode status = U_ZERO_ERROR;
839
// now try to use the default GMT time zone
840
GregorianCalendar *greenwichcalendar =
841
new GregorianCalendar(1997, 3, 4, 23, 0, status);
842
failure(status, "new GregorianCalendar");
843
//*****************************greenwichcalendar.setTimeZone(TimeZone.getDefault());
844
//greenwichcalendar.set(1997, 3, 4, 23, 0);
845
// try anything to set hour to 23:00 !!!
846
greenwichcalendar->set(Calendar::HOUR_OF_DAY, 23);
848
UDate greenwichdate = greenwichcalendar->getTime(status);
850
UnicodeString DATA [] = {
851
UnicodeString("simple format: "), UnicodeString("04/04/97 23:00 GMT"),
852
UnicodeString("MM/dd/yy HH:mm z"),
853
UnicodeString("full format: "), UnicodeString("Friday, April 4, 1997 11:00:00 o'clock PM GMT"),
854
UnicodeString("EEEE, MMMM d, yyyy h:mm:ss 'o''clock' a z"),
855
UnicodeString("long format: "), UnicodeString("April 4, 1997 11:00:00 PM GMT"),
856
UnicodeString("MMMM d, yyyy h:mm:ss a z"),
857
UnicodeString("default format: "), UnicodeString("04-Apr-97 11:00:00 PM"),
858
UnicodeString("dd-MMM-yy h:mm:ss a"),
859
UnicodeString("short format: "), UnicodeString("4/4/97 11:00 PM"),
860
UnicodeString("M/d/yy h:mm a")
862
int32_t DATA_length = (int32_t)(sizeof(DATA) / sizeof(DATA[0]));
864
for (int32_t i=0; i<DATA_length; i+=3) {
865
DateFormat *fmt = new SimpleDateFormat(DATA[i+2], Locale::getEnglish(), status);
866
if(failure(status, "new SimpleDateFormat")) break;
867
fmt->setCalendar(*greenwichcalendar);
868
UnicodeString result;
869
result = fmt->format(greenwichdate, result);
870
logln(DATA[i] + result);
871
if (result != DATA[i+1])
872
errln("FAIL: Expected " + DATA[i+1] + ", got " + result);
877
TimeZone::adoptDefault(saveDefault);
880
delete greenwichcalendar;
886
// -------------------------------------
889
* Test the formatting of dates in different locales.
892
DateFormatTest::TestLocaleDateFormat() // Bug 495
894
UDate testDate = date(97, Calendar::SEPTEMBER, 15);
895
DateFormat *dfFrench = DateFormat::createDateTimeInstance(DateFormat::FULL,
896
DateFormat::FULL, Locale::getFrench());
897
DateFormat *dfUS = DateFormat::createDateTimeInstance(DateFormat::FULL,
898
DateFormat::FULL, Locale::getUS());
899
UnicodeString expectedFRENCH ( "lundi 15 septembre 1997 00 h 00 GMT-07:00" );
900
//UnicodeString expectedUS ( "Monday, September 15, 1997 12:00:00 o'clock AM PDT" );
901
UnicodeString expectedUS ( "Monday, September 15, 1997 12:00:00 AM PDT" );
902
logln((UnicodeString)"Date set to : " + dateToString(testDate));
904
dfFrench->format(testDate, out);
905
logln((UnicodeString)"Date Formated with French Locale " + out);
906
if (!(out == expectedFRENCH))
907
errln((UnicodeString)"FAIL: Expected " + expectedFRENCH);
909
dfUS->format(testDate, out);
910
logln((UnicodeString)"Date Formated with US Locale " + out);
911
if (!(out == expectedUS))
912
errln((UnicodeString)"FAIL: Expected " + expectedUS);
918
* Test DateFormat(Calendar) API
920
void DateFormatTest::TestDateFormatCalendar() {
921
DateFormat *date=0, *time=0, *full=0;
926
UErrorCode ec = U_ZERO_ERROR;
928
/* Create a formatter for date fields. */
929
date = DateFormat::createDateInstance(DateFormat::kShort, Locale::getUS());
931
errln("FAIL: createDateInstance failed");
935
/* Create a formatter for time fields. */
936
time = DateFormat::createTimeInstance(DateFormat::kShort, Locale::getUS());
938
errln("FAIL: createTimeInstance failed");
942
/* Create a full format for output */
943
full = DateFormat::createDateTimeInstance(DateFormat::kFull, DateFormat::kFull,
946
errln("FAIL: createInstance failed");
950
/* Create a calendar */
951
cal = Calendar::createInstance(Locale::getUS(), ec);
952
if (cal == NULL || U_FAILURE(ec)) {
953
errln((UnicodeString)"FAIL: Calendar::createInstance failed with " +
960
str = UnicodeString("4/5/2001", "");
962
date->parse(str, *cal, pos);
963
if (pos.getIndex() != str.length()) {
964
errln((UnicodeString)"FAIL: DateFormat::parse(4/5/2001) failed at " +
970
str = UnicodeString("5:45 PM", "");
972
time->parse(str, *cal, pos);
973
if (pos.getIndex() != str.length()) {
974
errln((UnicodeString)"FAIL: DateFormat::parse(17:45) failed at " +
980
when = cal->getTime(ec);
982
errln((UnicodeString)"FAIL: cal->getTime() failed with " + u_errorName(ec));
986
full->format(when, str);
987
// Thursday, April 5, 2001 5:45:00 PM PDT 986517900000
988
if (when == 986517900000.0) {
989
logln("Ok: Parsed result: " + str);
991
errln("FAIL: Parsed result: " + str + ", exp 4/5/2001 5:45 PM");