void TestPartialParse994() { int32_t pos; UDateFormat *f; UErrorCode status = U_ZERO_ERROR; UChar *s; UChar *fmtChars; UDate d, null; null=0; /* this is supposed to open default date format, but later on it treats it like it is "en_US" - very bad if you try to run the tests on machine where default locale is NOT "en_US" */ /* f = udat_open(UDAT_DEFAULT, UDAT_SHORT, NULL, NULL, 0, &status); */ f = udat_open(UDAT_DEFAULT, UDAT_SHORT, "en_US", NULL, 0, NULL, 0,&status); if(U_FAILURE(status)){ log_data_err("FAIL: ErrorCode received during test: %s (Are you missing data?)\n", myErrorName(status)); return; } s=(UChar*)malloc(sizeof(UChar) * (strlen("01/01/1997 10:11:42 AM")+1) ); u_uastrcpy(s, "01/01/1997 10:11:42 AM"); pos=0; d = udat_parse(f, s, u_strlen(s), &pos, &status); if(U_FAILURE(status)) { log_data_err("FAIL: could not parse - exitting"); return; } fmtChars = myDateFormat(f, d); if(fmtChars) { log_verbose("%s\n", fmtChars); } else { log_data_err("FAIL: could not format \n"); return; } tryPat994(f, "yy/MM/dd HH:mm:ss", "97/01/01 10:11:42", d); tryPat994(f, "yy/MM/dd HH:mm:ss", "97/01/01 10:", null); tryPat994(f, "yy/MM/dd HH:mm:ss", "97/01/01 10", null); tryPat994(f, "yy/MM/dd HH:mm:ss", "97/01/01 ", null); tryPat994(f, "yy/MM/dd HH:mm:ss", "97/01/01", null); udat_close(f); free(s); }
/* PAL Function: GetLocaleTimeFormat Obtains time format information (in ICU format, it needs to be coverted to .NET Format). Returns 1 for success, 0 otherwise */ extern "C" int32_t GetLocaleTimeFormat(const UChar* localeName, int shortFormat, UChar* value, int32_t valueLength) { UErrorCode err = U_ZERO_ERROR; char locale[ULOC_FULLNAME_CAPACITY]; GetLocale(localeName, locale, ULOC_FULLNAME_CAPACITY, false, &err); if (U_FAILURE(err)) { return UErrorCodeToBool(U_ILLEGAL_ARGUMENT_ERROR); } UDateFormatStyle style = (shortFormat != 0) ? UDAT_SHORT : UDAT_MEDIUM; UDateFormat* pFormat = udat_open(style, UDAT_NONE, locale, nullptr, 0, nullptr, 0, &err); UDateFormatHolder formatHolder(pFormat, err); if (U_FAILURE(err)) return UErrorCodeToBool(err); udat_toPattern(pFormat, false, value, valueLength, &err); return UErrorCodeToBool(err); }
static void TestExtremeDates() { UDateFormat *fmt; UErrorCode ec; UChar buf[256]; char cbuf[256]; const double small = 1000; /* 1 sec */ const double large = 1e+30; /* well beyond usable UDate range */ /* There is no need to test larger values from 1e+30 to 1e+300; the failures occur around 1e+27, and never above 1e+30. */ ec = U_ZERO_ERROR; fmt = udat_open(UDAT_LONG, UDAT_LONG, "en_US", 0, 0, 0, 0, &ec); if (U_FAILURE(ec)) { log_data_err("FAIL: udat_open (%s) (Are you missing data?)\n", u_errorName(ec)); return; } _aux2ExtremeDates(fmt, small, large, buf, LEN(buf), cbuf, 0, &ec); udat_close(fmt); }
/* Test u_formatMessage() and u_parseMessage() , format and parse sequence and round trip */ static void TestSampleFormatAndParse(void) { UChar *result, *tzID, *str; UChar pattern[100]; UChar expected[100]; int32_t resultLengthOut, resultlength; UCalendar *cal; UDate d1,d; UDateFormat *def1; UErrorCode status = U_ZERO_ERROR; int32_t value = 0; UChar ret[30]; ctest_setTimeZone(NULL, &status); log_verbose("Testing format and parse\n"); str=(UChar*)malloc(sizeof(UChar) * 25); u_uastrcpy(str, "disturbance in force"); tzID=(UChar*)malloc(sizeof(UChar) * 4); u_uastrcpy(tzID, "PST"); cal=ucal_open(tzID, u_strlen(tzID), "en_US", UCAL_TRADITIONAL, &status); if(U_FAILURE(status)){ log_data_err("error in ucal_open caldef : %s - (Are you missing data?)\n", myErrorName(status) ); } ucal_setDateTime(cal, 1999, UCAL_MARCH, 18, 0, 0, 0, &status); d1=ucal_getMillis(cal, &status); if(U_FAILURE(status)){ log_data_err("Error: failure in get millis: %s - (Are you missing data?)\n", myErrorName(status) ); } log_verbose("\nTesting with pattern test#4"); u_uastrcpy(pattern, "On {0, date, long}, there was a {1} on planet {2,number,integer}"); u_uastrcpy(expected, "On March 18, 1999, there was a disturbance in force on planet 7"); resultlength=1; result=(UChar*)malloc(sizeof(UChar) * resultlength); resultLengthOut=u_formatMessage( "en_US", pattern, u_strlen(pattern), result, resultlength, &status, d1, str, 7); if(status==U_BUFFER_OVERFLOW_ERROR) { status=U_ZERO_ERROR; resultlength=resultLengthOut+1; result=(UChar*)realloc(result, sizeof(UChar) * resultlength); u_formatMessage( "en_US", pattern, u_strlen(pattern), result, resultlength, &status, d1, str, 7); } if(U_FAILURE(status)){ log_data_err("ERROR: failure in message format test#4: %s (Are you missing data?)\n", myErrorName(status)); } else if(u_strcmp(result, expected)==0) log_verbose("PASS: MessagFormat successful on test#4\n"); else{ log_err("FAIL: Error in MessageFormat on test#4\n GOT: %s EXPECTED: %s\n", austrdup(result), austrdup(expected) ); } /*try to parse this and check*/ log_verbose("\nTesting the parse Message test#5\n"); u_parseMessage("en_US", pattern, u_strlen(pattern), result, u_strlen(result), &status, &d, ret, &value); if(U_FAILURE(status)){ log_data_err("ERROR: error in parsing: test#5: %s (Are you missing data?)\n", myErrorName(status)); } else if(value!=7 && u_strcmp(str,ret)!=0) log_err("FAIL: Error in parseMessage on test#5 \n"); else log_verbose("PASS: parseMessage successful on test#5\n"); def1 = udat_open(UDAT_DEFAULT,UDAT_DEFAULT ,NULL, NULL, 0, NULL,0,&status); if(U_FAILURE(status)) { log_data_err("error in creating the dateformat using short date and time style: %s (Are you missing data?)\n", myErrorName(status)); }else{ if(u_strcmp(myDateFormat(def1, d), myDateFormat(def1, d1))==0) log_verbose("PASS: parseMessage successful test#5\n"); else{ log_err("FAIL: parseMessage didn't parse the date successfully\n GOT: %s EXPECTED %s\n", austrdup(myDateFormat(def1,d)), austrdup(myDateFormat(def1,d1)) ); } } udat_close(def1); ucal_close(cal); free(result); free(str); free(tzID); ctest_resetTimeZone(); }
/* Function: EnumSymbols Enumerates all of the symbols of a type for a locale and calendar and invokes a callback for each value. */ static int32_t EnumSymbols(const char* locale, CalendarId calendarId, UDateFormatSymbolType type, int32_t startIndex, EnumCalendarInfoCallback callback, const void* context) { UErrorCode err = U_ZERO_ERROR; UDateFormat* pFormat = udat_open(UDAT_DEFAULT, UDAT_DEFAULT, locale, NULL, 0, NULL, 0, &err); if (U_FAILURE(err)) return FALSE; char localeWithCalendarName[ULOC_FULLNAME_CAPACITY]; strncpy(localeWithCalendarName, locale, ULOC_FULLNAME_CAPACITY); uloc_setKeywordValue("calendar", GetCalendarName(calendarId), localeWithCalendarName, ULOC_FULLNAME_CAPACITY, &err); UCalendar* pCalendar = ucal_open(NULL, 0, localeWithCalendarName, UCAL_DEFAULT, &err); if (U_FAILURE(err)) { udat_close(pFormat); return FALSE; } udat_setCalendar(pFormat, pCalendar); int32_t symbolCount = udat_countSymbols(pFormat, type); UChar stackSymbolBuf[100]; UChar* symbolBuf; for (int32_t i = startIndex; U_SUCCESS(err) && i < symbolCount; i++) { UErrorCode ignore = U_ZERO_ERROR; int symbolLen = udat_getSymbols(pFormat, type, i, NULL, 0, &ignore) + 1; if (symbolLen <= sizeof(stackSymbolBuf) / sizeof(stackSymbolBuf[0])) { symbolBuf = stackSymbolBuf; } else { symbolBuf = calloc(symbolLen, sizeof(UChar)); if (symbolBuf == NULL) { err = U_MEMORY_ALLOCATION_ERROR; break; } } udat_getSymbols(pFormat, type, i, symbolBuf, symbolLen, &err); if (U_SUCCESS(err)) { callback(symbolBuf, context); } if (symbolBuf != stackSymbolBuf) { free(symbolBuf); } } udat_close(pFormat); ucal_close(pCalendar); return UErrorCodeToBool(err); }
static inline UDateFormat* createShortDateFormatter() { const UChar gmtTimezone[3] = {'G', 'M', 'T'}; UErrorCode status = U_ZERO_ERROR; return udat_open(UDAT_NONE, UDAT_SHORT, defaultLanguage().utf8().data(), gmtTimezone, WTF_ARRAY_LENGTH(gmtTimezone), 0, -1, &status); }
/* Print out a calendar for c's current year */ static void print_year(UCalendar *c, UChar *days [], UChar *months [], UBool useLongNames, int32_t fdow, UErrorCode *status) { int32_t width, pad, i, j; int32_t lens [DAY_COUNT]; UNumberFormat *nfmt; UDateFormat *dfmt; UChar s [BUF_SIZE]; const UChar pat [] = { 0x0079, 0x0079, 0x0079, 0x0079 }; int32_t len = 4; UCalendar *left_cal, *right_cal; int32_t left_day, right_day; int32_t left_firstday, right_firstday, left_current, right_current; int32_t left_month, right_month; if(U_FAILURE(*status)) return; /* Alias */ left_cal = c; /* ========== Generate the header containing the year (only) */ /* Open a formatter with a month and year only pattern */ dfmt = udat_open(UDAT_IGNORE,UDAT_IGNORE,NULL,NULL,0,pat, len, status); /* Format the date */ udat_format(dfmt, ucal_getMillis(left_cal, status), s, BUF_SIZE, 0, status); /* ========== Get the month and day names */ get_days(dfmt, days, useLongNames, fdow, status); get_months(dfmt, months, useLongNames, status); /* ========== Print the header, centered */ /* Calculate widths for justification */ width = 6; /* 6 spaces, 1 between each day name */ for(i = 0; i < DAY_COUNT; ++i) { lens[i] = u_strlen(days[i]); width += lens[i]; } /* width is the width for 1 calendar; we are displaying in 2 cols with MARGIN_WIDTH spaces between months */ /* Print the header, centered among the day names */ pad = 2 * width + MARGIN_WIDTH - u_strlen(s); indent(pad / 2, stdout); uprint(s, stdout, status); putc('\n', stdout); putc('\n', stdout); /* Generate a copy of the calendar to use */ right_cal = ucal_open(0, -1, uloc_getDefault(), UCAL_TRADITIONAL, status); ucal_setMillis(right_cal, ucal_getMillis(left_cal, status), status); /* Open the formatter */ nfmt = unum_open(UNUM_DECIMAL,NULL, 0,NULL,NULL, status); /* ========== Calculate and display the months, two at a time */ for(i = 0; i < MONTH_COUNT - 1; i += 2) { /* Print the month names for the two current months */ pad = width - u_strlen(months[i]); indent(pad / 2, stdout); uprint(months[i], stdout, status); indent(pad / 2 + MARGIN_WIDTH, stdout); pad = width - u_strlen(months[i + 1]); indent(pad / 2, stdout); uprint(months[i + 1], stdout, status); putc('\n', stdout); /* Print the day names, twice */ print_days(days, stdout, status); indent(MARGIN_WIDTH, stdout); print_days(days, stdout, status); putc('\n', stdout); /* Setup the two calendars */ ucal_set(left_cal, UCAL_MONTH, i); ucal_set(left_cal, UCAL_DATE, 1); ucal_set(right_cal, UCAL_MONTH, i + 1); ucal_set(right_cal, UCAL_DATE, 1); left_firstday = ucal_get(left_cal, UCAL_DAY_OF_WEEK, status); right_firstday = ucal_get(right_cal, UCAL_DAY_OF_WEEK, status); /* The day of the week for the first day of the month is based on 1-based days of the week. However, the days were reordered when placed in the days array. Account for this here by offsetting by the first day of the week for the locale, which is also 1-based. */ /* We need to mod by DAY_COUNT since fdow can be > firstday. IE, if fdow = 2 = Monday (like in France) and the first day of the month is a 1 = Sunday, we want firstday to be 6, not -1 */ left_firstday += (DAY_COUNT - fdow); left_firstday %= DAY_COUNT; right_firstday += (DAY_COUNT - fdow); right_firstday %= DAY_COUNT; left_current = left_firstday; right_current = right_firstday; left_day = ucal_get(left_cal, UCAL_DATE, status); right_day = ucal_get(right_cal, UCAL_DATE, status); left_month = ucal_get(left_cal, UCAL_MONTH, status); right_month = ucal_get(right_cal, UCAL_MONTH, status); /* Finally, print out the days */ while(left_month == i || right_month == i + 1) { /* If the left month is finished printing, but the right month still has days to be printed, indent the width of the days strings and reset the left calendar's current day to 0 */ if(left_month != i && right_month == i + 1) { indent(width + 1, stdout); left_current = 0; } while(left_month == i) { /* If the day is the first, indent the correct number of spaces for the first week */ if(left_day == 1) { for(j = 0; j < left_current; ++j) indent(lens[j] + 1, stdout); } /* Format the current day string */ unum_format(nfmt, left_day, s, BUF_SIZE, 0, status); /* Calculate the justification and indent */ pad = lens[left_current] - u_strlen(s); indent(pad, stdout); /* Print the day number out, followed by a space */ uprint(s, stdout, status); putc(' ', stdout); /* Update the current day */ ++left_current; left_current %= DAY_COUNT; /* Go to the next day */ ucal_add(left_cal, UCAL_DATE, 1, status); left_day = ucal_get(left_cal, UCAL_DATE, status); /* Determine the month */ left_month = ucal_get(left_cal, UCAL_MONTH, status); /* If we're at day 0 (first day of the week), break and go to the next month */ if(left_current == 0) { break; } }; /* If the current day isn't 0, indent to make up for missing days at the end of the month */ if(left_current != 0) { for(j = left_current; j < DAY_COUNT; ++j) indent(lens[j] + 1, stdout); } /* Indent between the two months */ indent(MARGIN_WIDTH, stdout); while(right_month == i + 1) { /* If the day is the first, indent the correct number of spaces for the first week */ if(right_day == 1) { for(j = 0; j < right_current; ++j) indent(lens[j] + 1, stdout); } /* Format the current day string */ unum_format(nfmt, right_day, s, BUF_SIZE, 0, status); /* Calculate the justification and indent */ pad = lens[right_current] - u_strlen(s); indent(pad, stdout); /* Print the day number out, followed by a space */ uprint(s, stdout, status); putc(' ', stdout); /* Update the current day */ ++right_current; right_current %= DAY_COUNT; /* Go to the next day */ ucal_add(right_cal, UCAL_DATE, 1, status); right_day = ucal_get(right_cal, UCAL_DATE, status); /* Determine the month */ right_month = ucal_get(right_cal, UCAL_MONTH, status); /* If we're at day 0 (first day of the week), break out */ if(right_current == 0) { break; } }; /* Output a newline */ putc('\n', stdout); } /* Output a trailing newline */ putc('\n', stdout); } /* Clean up */ free_months(months); free_days(days); udat_close(dfmt); unum_close(nfmt); ucal_close(right_cal); }
/*Testing udat_getSymbols() and udat_setSymbols() and udat_countSymbols()*/ static void TestSymbols() { UDateFormat *def, *fr; UErrorCode status = U_ZERO_ERROR; UChar *value=NULL; UChar *result = NULL; int32_t resultlength; int32_t resultlengthout; UChar *pattern; /*creating a dateformat with french locale */ log_verbose("\ncreating a date format with french locale\n"); fr = udat_open(UDAT_FULL, UDAT_DEFAULT, "fr_FR", NULL, 0, NULL, 0, &status); if(U_FAILURE(status)) { log_data_err("error in creating the dateformat using full time style with french locale -> %s (Are you missing data?)\n", myErrorName(status) ); return; } /*creating a default dateformat */ log_verbose("\ncreating a date format with default locale\n"); /* this is supposed to open default date format, but later on it treats it like it is "en_US" - very bad if you try to run the tests on machine where default locale is NOT "en_US" */ /* def = udat_open(UDAT_DEFAULT,UDAT_DEFAULT ,NULL, NULL, 0, &status); */ def = udat_open(UDAT_DEFAULT,UDAT_DEFAULT ,"en_US", NULL, 0, NULL, 0, &status); if(U_FAILURE(status)) { log_err("error in creating the dateformat using short date and time style\n %s\n", myErrorName(status) ); return; } /*Testing countSymbols, getSymbols and setSymbols*/ log_verbose("\nTesting countSymbols\n"); /*since the month names has the last string empty and week names are 1 based 1.e first string in the weeknames array is empty */ if(udat_countSymbols(def, UDAT_ERAS)!=2 || udat_countSymbols(def, UDAT_MONTHS)!=12 || udat_countSymbols(def, UDAT_SHORT_MONTHS)!=12 || udat_countSymbols(def, UDAT_WEEKDAYS)!=8 || udat_countSymbols(def, UDAT_SHORT_WEEKDAYS)!=8 || udat_countSymbols(def, UDAT_AM_PMS)!=2 || udat_countSymbols(def, UDAT_QUARTERS) != 4 || udat_countSymbols(def, UDAT_SHORT_QUARTERS) != 4 || udat_countSymbols(def, UDAT_LOCALIZED_CHARS)!=1) { log_err("FAIL: error in udat_countSymbols\n"); } else log_verbose("PASS: udat_countSymbols() successful\n"); /*testing getSymbols*/ log_verbose("\nTesting getSymbols\n"); pattern=(UChar*)malloc(sizeof(UChar) * 10); u_uastrcpy(pattern, "jeudi"); resultlength=0; resultlengthout=udat_getSymbols(fr, UDAT_WEEKDAYS, 5 , NULL, resultlength, &status); if(status==U_BUFFER_OVERFLOW_ERROR) { status=U_ZERO_ERROR; resultlength=resultlengthout+1; if(result != NULL) { free(result); result = NULL; } result=(UChar*)malloc(sizeof(UChar) * resultlength); udat_getSymbols(fr, UDAT_WEEKDAYS, 5, result, resultlength, &status); } if(U_FAILURE(status)) { log_err("FAIL: Error in udat_getSymbols().... %s\n", myErrorName(status) ); } else log_verbose("PASS: getSymbols succesful\n"); if(u_strcmp(result, pattern)==0) log_verbose("PASS: getSymbols retrieved the right value\n"); else log_data_err("FAIL: getSymbols retrieved the wrong value\n"); /*run series of tests to test getsymbols regressively*/ log_verbose("\nTesting getSymbols() regressively\n"); VerifygetSymbols(fr, UDAT_WEEKDAYS, 1, "dimanche"); VerifygetSymbols(def, UDAT_WEEKDAYS, 1, "Sunday"); VerifygetSymbols(fr, UDAT_SHORT_WEEKDAYS, 7, "sam."); VerifygetSymbols(def, UDAT_SHORT_WEEKDAYS, 7, "Sat"); VerifygetSymbols(def, UDAT_MONTHS, 11, "December"); VerifygetSymbols(def, UDAT_MONTHS, 0, "January"); VerifygetSymbols(fr, UDAT_ERAS, 0, "av. J.-C."); VerifygetSymbols(def, UDAT_AM_PMS, 0, "AM"); VerifygetSymbols(def, UDAT_AM_PMS, 1, "PM"); VerifygetSymbols(fr, UDAT_SHORT_MONTHS, 0, "janv."); VerifygetSymbols(def, UDAT_SHORT_MONTHS, 11, "Dec"); VerifygetSymbols(fr, UDAT_QUARTERS, 0, "1er trimestre"); VerifygetSymbols(def, UDAT_QUARTERS, 3, "4th quarter"); VerifygetSymbols(fr, UDAT_SHORT_QUARTERS, 1, "T2"); VerifygetSymbols(def, UDAT_SHORT_QUARTERS, 2, "Q3"); VerifygetSymbols(def,UDAT_LOCALIZED_CHARS, 0, "GyMdkHmsSEDFwWahKzYeugAZvcLQqV"); if(result != NULL) { free(result); result = NULL; } free(pattern); log_verbose("\nTesting setSymbols\n"); /*applying the pattern so that setSymbolss works */ resultlength=0; resultlengthout=udat_toPattern(fr, FALSE, NULL, resultlength, &status); if(status==U_BUFFER_OVERFLOW_ERROR) { status=U_ZERO_ERROR; resultlength=resultlengthout + 1; pattern=(UChar*)malloc(sizeof(UChar) * resultlength); udat_toPattern(fr, FALSE, pattern, resultlength, &status); } if(U_FAILURE(status)) { log_err("FAIL: error in extracting the pattern from UNumberFormat\n %s\n", myErrorName(status) ); } udat_applyPattern(def, FALSE, pattern, u_strlen(pattern)); resultlength=0; resultlengthout=udat_toPattern(def, FALSE, NULL, resultlength,&status); if(status==U_BUFFER_OVERFLOW_ERROR) { status=U_ZERO_ERROR; resultlength=resultlengthout + 1; if(result != NULL) { free(result); result = NULL; } result=(UChar*)malloc(sizeof(UChar) * resultlength); udat_toPattern(fr, FALSE,result, resultlength, &status); } if(U_FAILURE(status)) { log_err("FAIL: error in extracting the pattern from UNumberFormat\n %s\n", myErrorName(status) ); } if(u_strcmp(result, pattern)==0) log_verbose("Pattern applied properly\n"); else log_err("pattern could not be applied properly\n"); free(pattern); /*testing set symbols */ resultlength=0; resultlengthout=udat_getSymbols(fr, UDAT_MONTHS, 11 , NULL, resultlength, &status); if(status==U_BUFFER_OVERFLOW_ERROR){ status=U_ZERO_ERROR; resultlength=resultlengthout+1; if(result != NULL) { free(result); result = NULL; } result=(UChar*)malloc(sizeof(UChar) * resultlength); udat_getSymbols(fr, UDAT_MONTHS, 11, result, resultlength, &status); } if(U_FAILURE(status)) log_err("FAIL: error in getSymbols() %s\n", myErrorName(status) ); resultlength=resultlengthout+1; udat_setSymbols(def, UDAT_MONTHS, 11, result, resultlength, &status); if(U_FAILURE(status)) { log_err("FAIL: Error in udat_setSymbols() : %s\n", myErrorName(status) ); } else log_verbose("PASS: SetSymbols successful\n"); resultlength=0; resultlengthout=udat_getSymbols(def, UDAT_MONTHS, 11, NULL, resultlength, &status); if(status==U_BUFFER_OVERFLOW_ERROR){ status=U_ZERO_ERROR; resultlength=resultlengthout+1; value=(UChar*)malloc(sizeof(UChar) * resultlength); udat_getSymbols(def, UDAT_MONTHS, 11, value, resultlength, &status); } if(U_FAILURE(status)) log_err("FAIL: error in retrieving the value using getSymbols i.e roundtrip\n"); if(u_strcmp(result, value)!=0) log_data_err("FAIL: Error in settting and getting symbols\n"); else log_verbose("PASS: setSymbols successful\n"); /*run series of tests to test setSymbols regressively*/ log_verbose("\nTesting setSymbols regressively\n"); VerifysetSymbols(def, UDAT_ERAS, 0, "BeforeChrist"); VerifysetSymbols(def, UDAT_ERA_NAMES, 1, "AnnoDomini"); VerifysetSymbols(def, UDAT_WEEKDAYS, 1, "Sundayweek"); VerifysetSymbols(def, UDAT_SHORT_WEEKDAYS, 7, "Satweek"); VerifysetSymbols(def, UDAT_NARROW_WEEKDAYS, 4, "M"); VerifysetSymbols(def, UDAT_STANDALONE_WEEKDAYS, 1, "Sonntagweek"); VerifysetSymbols(def, UDAT_STANDALONE_SHORT_WEEKDAYS, 7, "Sams"); VerifysetSymbols(def, UDAT_STANDALONE_NARROW_WEEKDAYS, 4, "V"); VerifysetSymbols(fr, UDAT_MONTHS, 11, "december"); VerifysetSymbols(fr, UDAT_SHORT_MONTHS, 0, "Jan"); VerifysetSymbols(fr, UDAT_NARROW_MONTHS, 1, "R"); VerifysetSymbols(fr, UDAT_STANDALONE_MONTHS, 11, "dezember"); VerifysetSymbols(fr, UDAT_STANDALONE_SHORT_MONTHS, 7, "Aug"); VerifysetSymbols(fr, UDAT_STANDALONE_NARROW_MONTHS, 2, "M"); VerifysetSymbols(fr, UDAT_QUARTERS, 0, "1. Quart"); VerifysetSymbols(fr, UDAT_SHORT_QUARTERS, 1, "QQ2"); VerifysetSymbols(fr, UDAT_STANDALONE_QUARTERS, 2, "3rd Quar."); VerifysetSymbols(fr, UDAT_STANDALONE_SHORT_QUARTERS, 3, "4QQ"); /*run series of tests to test get and setSymbols regressively*/ log_verbose("\nTesting get and set symbols regressively\n"); VerifygetsetSymbols(fr, def, UDAT_WEEKDAYS, 1); VerifygetsetSymbols(fr, def, UDAT_WEEKDAYS, 7); VerifygetsetSymbols(fr, def, UDAT_SHORT_WEEKDAYS, 1); VerifygetsetSymbols(fr, def, UDAT_SHORT_WEEKDAYS, 7); VerifygetsetSymbols(fr, def, UDAT_MONTHS, 0); VerifygetsetSymbols(fr, def, UDAT_SHORT_MONTHS, 0); VerifygetsetSymbols(fr, def, UDAT_ERAS,1); VerifygetsetSymbols(fr, def, UDAT_LOCALIZED_CHARS, 0); VerifygetsetSymbols(fr, def, UDAT_AM_PMS, 1); /*closing*/ udat_close(fr); udat_close(def); if(result != NULL) { free(result); result = NULL; } free(value); }
static void TestRelativeDateFormat() { UDate today = 0.0; const UDateFormatStyle * stylePtr; const UChar ** monthPtnPtr; UErrorCode status = U_ZERO_ERROR; UCalendar * ucal = ucal_open(trdfZone, -1, trdfLocale, UCAL_GREGORIAN, &status); if ( U_SUCCESS(status) ) { int32_t year, month, day; ucal_setMillis(ucal, ucal_getNow(), &status); year = ucal_get(ucal, UCAL_YEAR, &status); month = ucal_get(ucal, UCAL_MONTH, &status); day = ucal_get(ucal, UCAL_DATE, &status); ucal_setDateTime(ucal, year, month, day, 18, 49, 0, &status); /* set to today at 18:49:00 */ today = ucal_getMillis(ucal, &status); ucal_close(ucal); } if ( U_FAILURE(status) || today == 0.0 ) { log_data_err("Generate UDate for a specified time today fails, error %s - (Are you missing data?)\n", myErrorName(status) ); return; } for (stylePtr = dateStylesList, monthPtnPtr = monthPatnsList; *stylePtr != UDAT_NONE; ++stylePtr, ++monthPtnPtr) { UDateFormat* fmtRelDateTime; UDateFormat* fmtRelDate; UDateFormat* fmtTime; int32_t dayOffset, limit; UFieldPosition fp; UChar strDateTime[kDateAndTimeOutMax]; UChar strDate[kDateOrTimeOutMax]; UChar strTime[kDateOrTimeOutMax]; UChar * strPtr; int32_t dtpatLen; fmtRelDateTime = udat_open(UDAT_SHORT, *stylePtr | UDAT_RELATIVE, trdfLocale, trdfZone, -1, NULL, 0, &status); if ( U_FAILURE(status) ) { log_data_err("udat_open timeStyle SHORT dateStyle (%d | UDAT_RELATIVE) fails, error %s (Are you missing data?)\n", *stylePtr, myErrorName(status) ); continue; } fmtRelDate = udat_open(UDAT_NONE, *stylePtr | UDAT_RELATIVE, trdfLocale, trdfZone, -1, NULL, 0, &status); if ( U_FAILURE(status) ) { log_err("udat_open timeStyle NONE dateStyle (%d | UDAT_RELATIVE) fails, error %s\n", *stylePtr, myErrorName(status) ); udat_close(fmtRelDateTime); continue; } fmtTime = udat_open(UDAT_SHORT, UDAT_NONE, trdfLocale, trdfZone, -1, NULL, 0, &status); if ( U_FAILURE(status) ) { log_err("udat_open timeStyle SHORT dateStyle NONE fails, error %s\n", myErrorName(status) ); udat_close(fmtRelDateTime); udat_close(fmtRelDate); continue; } dtpatLen = udat_toPatternRelativeDate(fmtRelDateTime, strDate, kDateAndTimeOutMax, &status); if ( U_FAILURE(status) ) { log_err("udat_toPatternRelativeDate timeStyle SHORT dateStyle (%d | UDAT_RELATIVE) fails, error %s\n", *stylePtr, myErrorName(status) ); status = U_ZERO_ERROR; } else if ( u_strstr(strDate, *monthPtnPtr) == NULL || dtpatLen != u_strlen(strDate) ) { log_err("udat_toPatternRelativeDate timeStyle SHORT dateStyle (%d | UDAT_RELATIVE) date pattern incorrect\n", *stylePtr ); } dtpatLen = udat_toPatternRelativeTime(fmtRelDateTime, strTime, kDateAndTimeOutMax, &status); if ( U_FAILURE(status) ) { log_err("udat_toPatternRelativeTime timeStyle SHORT dateStyle (%d | UDAT_RELATIVE) fails, error %s\n", *stylePtr, myErrorName(status) ); status = U_ZERO_ERROR; } else if ( u_strstr(strTime, minutesPatn) == NULL || dtpatLen != u_strlen(strTime) ) { log_err("udat_toPatternRelativeTime timeStyle SHORT dateStyle (%d | UDAT_RELATIVE) time pattern incorrect\n", *stylePtr ); } dtpatLen = udat_toPattern(fmtRelDateTime, FALSE, strDateTime, kDateAndTimeOutMax, &status); if ( U_FAILURE(status) ) { log_err("udat_toPattern timeStyle SHORT dateStyle (%d | UDAT_RELATIVE) fails, error %s\n", *stylePtr, myErrorName(status) ); status = U_ZERO_ERROR; } else if ( u_strstr(strDateTime, strDate) == NULL || u_strstr(strDateTime, strTime) == NULL || dtpatLen != u_strlen(strDateTime) ) { log_err("udat_toPattern timeStyle SHORT dateStyle (%d | UDAT_RELATIVE) dateTime pattern incorrect\n", *stylePtr ); } udat_applyPatternRelative(fmtRelDateTime, strDate, u_strlen(strDate), newTimePatn, u_strlen(newTimePatn), &status); if ( U_FAILURE(status) ) { log_err("udat_applyPatternRelative timeStyle SHORT dateStyle (%d | UDAT_RELATIVE) fails, error %s\n", *stylePtr, myErrorName(status) ); status = U_ZERO_ERROR; } else { udat_toPattern(fmtRelDateTime, FALSE, strDateTime, kDateAndTimeOutMax, &status); if ( U_FAILURE(status) ) { log_err("udat_toPattern timeStyle SHORT dateStyle (%d | UDAT_RELATIVE) fails, error %s\n", *stylePtr, myErrorName(status) ); status = U_ZERO_ERROR; } else if ( u_strstr(strDateTime, newTimePatn) == NULL ) { log_err("udat_applyPatternRelative timeStyle SHORT dateStyle (%d | UDAT_RELATIVE) didn't update time pattern\n", *stylePtr ); } } udat_applyPatternRelative(fmtRelDateTime, strDate, u_strlen(strDate), strTime, u_strlen(strTime), &status); /* restore original */ fp.field = UDAT_MINUTE_FIELD; for (dayOffset = -2, limit = 2; dayOffset <= limit; ++dayOffset) { UDate dateToUse = today + (float)dayOffset*dayInterval; udat_format(fmtRelDateTime, dateToUse, strDateTime, kDateAndTimeOutMax, &fp, &status); if ( U_FAILURE(status) ) { log_err("udat_format timeStyle SHORT dateStyle (%d | UDAT_RELATIVE) fails, error %s\n", *stylePtr, myErrorName(status) ); status = U_ZERO_ERROR; } else { udat_format(fmtRelDate, dateToUse, strDate, kDateOrTimeOutMax, NULL, &status); if ( U_FAILURE(status) ) { log_err("udat_format timeStyle NONE dateStyle (%d | UDAT_RELATIVE) fails, error %s\n", *stylePtr, myErrorName(status) ); status = U_ZERO_ERROR; } else if ( u_strstr(strDateTime, strDate) == NULL ) { log_err("relative date string not found in udat_format timeStyle SHORT dateStyle (%d | UDAT_RELATIVE)\n", *stylePtr ); } udat_format(fmtTime, dateToUse, strTime, kDateOrTimeOutMax, NULL, &status); if ( U_FAILURE(status) ) { log_err("udat_format timeStyle SHORT dateStyle NONE fails, error %s\n", myErrorName(status) ); status = U_ZERO_ERROR; } else if ( u_strstr(strDateTime, strTime) == NULL ) { log_err("time string not found in udat_format timeStyle SHORT dateStyle (%d | UDAT_RELATIVE)\n", *stylePtr ); } strPtr = u_strstr(strDateTime, minutesStr); if ( strPtr != NULL ) { int32_t beginIndex = strPtr - strDateTime; if ( fp.beginIndex != beginIndex ) { log_err("UFieldPosition beginIndex %d, expected %d, in udat_format timeStyle SHORT dateStyle (%d | UDAT_RELATIVE)\n", fp.beginIndex, beginIndex, *stylePtr ); } } else { log_err("minutes string not found in udat_format timeStyle SHORT dateStyle (%d | UDAT_RELATIVE)\n", *stylePtr ); } } } udat_close(fmtRelDateTime); udat_close(fmtRelDate); udat_close(fmtTime); } }
UDateFormat* LocaleICU::openDateFormat(UDateFormatStyle timeStyle, UDateFormatStyle dateStyle) const { const UChar gmtTimezone[3] = {'G', 'M', 'T'}; UErrorCode status = U_ZERO_ERROR; return udat_open(timeStyle, dateStyle, m_locale.data(), gmtTimezone, WTF_ARRAY_LENGTH(gmtTimezone), 0, -1, &status); }
ScopedDateFormat() { UErrorCode status = U_ZERO_ERROR; m_dateFormat = udat_open(UDAT_DEFAULT, UDAT_DEFAULT, defaultLanguage().utf8().data(), 0, -1, 0, -1, &status); }
void TestCzechMonths459() { int32_t lneed, pos; UChar *pattern=NULL, *tzID=NULL; UChar *juneStr, *julyStr; UDateFormat *fmt; UCalendar *cal; UDate june, july, d; UErrorCode status = U_ZERO_ERROR; UChar *date; ctest_setTimeZone(NULL, &status); fmt = udat_open(UDAT_FULL, UDAT_FULL, "cs", NULL, 0, NULL, 0, &status); if(U_FAILURE(status)){ log_data_err("Error in constructing the date format -> %s (Are you missing data?)\n", u_errorName(status)); ctest_resetTimeZone(); return; } lneed=0; lneed=udat_toPattern(fmt, TRUE, NULL, lneed, &status); if(status==U_BUFFER_OVERFLOW_ERROR){ status=U_ZERO_ERROR; pattern=(UChar*)malloc(sizeof(UChar) * (lneed+1) ); udat_toPattern(fmt, TRUE, pattern, lneed+1, &status); } if(U_FAILURE(status)){ log_err("Error in extracting the pattern\n"); } tzID=(UChar*)malloc(sizeof(UChar) * 4); u_uastrcpy(tzID, "GMT"); cal=ucal_open(tzID, u_strlen(tzID), "cs", UCAL_GREGORIAN, &status); if(U_FAILURE(status)){ log_err("error in ucal_open caldef : %s\n", myErrorName(status)); } ucal_setDate(cal, 1997, UCAL_JUNE, 15, &status); june=ucal_getMillis(cal, &status); ucal_setDate(cal, 1997, UCAL_JULY, 15, &status); july=ucal_getMillis(cal, &status); juneStr = myDateFormat(fmt, june); julyStr = myDateFormat(fmt, july); pos=0; if(juneStr == NULL) { log_data_err("Can't load juneStr. Quitting.\n"); return; } d = udat_parse(fmt, juneStr, u_strlen(juneStr), &pos, &status); date = myDateFormat(fmt, d); if(U_SUCCESS(status)){ UChar* out1 = myDateFormat(fmt, june); UChar* out2 = myDateFormat(fmt, d); if(u_strcmp(out1, out2) !=0) log_err("Error in handling the czech month june\n"); else log_verbose("Pass: Date = %s (czech month June)\n", aescstrdup(date, -1)); }else{ log_err("udat_parse failed. Error. %s\n",u_errorName(status)); } pos=0; d = udat_parse(fmt, julyStr, u_strlen(julyStr), &pos, &status); date = myDateFormat(fmt, d); if(u_strcmp(myDateFormat(fmt, july), myDateFormat(fmt, d) ) !=0) log_err("Error in handling the czech month july\n"); else log_verbose("Pass: Date = %s (czech month July)\n", aescstrdup(date, -1)); ctest_resetTimeZone(); udat_close(fmt); ucal_close(cal); free(pattern); free(tzID); }
/* {{{ */ static void datefmt_ctor(INTERNAL_FUNCTION_PARAMETERS) { char* locale; int locale_len = 0; zval* object; long date_type = 0; long time_type = 0; long calendar = UCAL_GREGORIAN; char* timezone_str = NULL; int timezone_str_len = 0; char* pattern_str = NULL; int pattern_str_len = 0; UChar* svalue = NULL; /* UTF-16 pattern_str */ int slength = 0; UChar* timezone_utf16 = NULL; /* UTF-16 timezone_str */ int timezone_utf16_len = 0; UCalendar ucal_obj = NULL; IntlDateFormatter_object* dfo; intl_error_reset( NULL TSRMLS_CC ); object = return_value; /* Parse parameters. */ if( zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "sll|sls", &locale, &locale_len, &date_type, &time_type, &timezone_str, &timezone_str_len, &calendar,&pattern_str, &pattern_str_len ) == FAILURE ) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "datefmt_create: unable to parse input parameters", 0 TSRMLS_CC ); zval_dtor(return_value); RETURN_NULL(); } INTL_CHECK_LOCALE_LEN_OBJ(locale_len, return_value); if (calendar != UCAL_TRADITIONAL && calendar != UCAL_GREGORIAN) { intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "datefmt_create: " "invalid value for calendar type; it must be one of " "IntlDateFormatter::TRADITIONAL (locale's default calendar) " "or IntlDateFormatter::GREGORIAN", 0 TSRMLS_CC); goto error; } DATE_FORMAT_METHOD_FETCH_OBJECT_NO_CHECK; if (DATE_FORMAT_OBJECT(dfo) != NULL) { intl_errors_set(INTL_DATA_ERROR_P(dfo), U_ILLEGAL_ARGUMENT_ERROR, "datefmt_create: cannot call constructor twice", 0 TSRMLS_CC); return; } /* Convert pattern (if specified) to UTF-16. */ if( pattern_str && pattern_str_len>0 ){ intl_convert_utf8_to_utf16(&svalue, &slength, pattern_str, pattern_str_len, &INTL_DATA_ERROR_CODE(dfo)); if (U_FAILURE(INTL_DATA_ERROR_CODE(dfo))) { /* object construction -> only set global error */ intl_error_set(NULL, INTL_DATA_ERROR_CODE(dfo), "datefmt_create: " "error converting pattern to UTF-16", 0 TSRMLS_CC); goto error; } } /* resources allocated from now on */ /* Convert pattern (if specified) to UTF-16. */ if( timezone_str && timezone_str_len >0 ){ intl_convert_utf8_to_utf16(&timezone_utf16, &timezone_utf16_len, timezone_str, timezone_str_len, &INTL_DATA_ERROR_CODE(dfo)); if (U_FAILURE(INTL_DATA_ERROR_CODE(dfo))) { intl_error_set(NULL, INTL_DATA_ERROR_CODE(dfo), "datefmt_create: " "error converting timezone_str to UTF-16", 0 TSRMLS_CC); goto error; } } if(locale_len == 0) { locale = INTL_G(default_locale); } if( pattern_str && pattern_str_len>0 ){ DATE_FORMAT_OBJECT(dfo) = udat_open(UDAT_IGNORE, UDAT_IGNORE, locale, timezone_utf16, timezone_utf16_len, svalue, slength, &INTL_DATA_ERROR_CODE(dfo)); } else { DATE_FORMAT_OBJECT(dfo) = udat_open(time_type, date_type, locale, timezone_utf16, timezone_utf16_len, svalue, slength, &INTL_DATA_ERROR_CODE(dfo)); } if (!U_FAILURE(INTL_DATA_ERROR_CODE(dfo))) { if (calendar != UCAL_TRADITIONAL) { ucal_obj = ucal_open(timezone_utf16, timezone_utf16_len, locale, calendar, &INTL_DATA_ERROR_CODE(dfo)); if (!U_FAILURE(INTL_DATA_ERROR_CODE(dfo))) { udat_setCalendar(DATE_FORMAT_OBJECT(dfo), ucal_obj); ucal_close(ucal_obj); } else { intl_error_set(NULL, INTL_DATA_ERROR_CODE(dfo), "datefmt_create" ": error opening calendar", 0 TSRMLS_CC); goto error; } } } else { intl_error_set(NULL, INTL_DATA_ERROR_CODE(dfo), "datefmt_create: date " "formatter creation failed", 0 TSRMLS_CC); goto error; } /* Set the class variables */ dfo->date_type = date_type; dfo->time_type = time_type; dfo->calendar = calendar; if( timezone_str && timezone_str_len > 0){ dfo->timezone_id = estrndup( timezone_str, timezone_str_len); } error: if (svalue) { efree(svalue); } if (timezone_utf16) { efree(timezone_utf16); } if (U_FAILURE(intl_error_get_code(NULL TSRMLS_CC))) { /* free_object handles partially constructed instances fine */ zval_dtor(return_value); RETVAL_NULL(); } }
/* {{{ */ static void datefmt_ctor(INTERNAL_FUNCTION_PARAMETERS) { zval *object; const char *locale_str; size_t locale_len = 0; Locale locale; zend_long date_type = 0; zend_long time_type = 0; zval *calendar_zv = NULL; Calendar *calendar = NULL; zend_long calendar_type; bool calendar_owned; zval *timezone_zv = NULL; TimeZone *timezone = NULL; bool explicit_tz; char* pattern_str = NULL; size_t pattern_str_len = 0; UChar* svalue = NULL; /* UTF-16 pattern_str */ int32_t slength = 0; IntlDateFormatter_object* dfo; intl_error_reset(NULL); object = return_value; /* Parse parameters. */ if (zend_parse_parameters(ZEND_NUM_ARGS(), "sll|zzs", &locale_str, &locale_len, &date_type, &time_type, &timezone_zv, &calendar_zv, &pattern_str, &pattern_str_len) == FAILURE) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "datefmt_create: " "unable to parse input parameters", 0); Z_OBJ_P(return_value) = NULL; return; } INTL_CHECK_LOCALE_LEN_OBJ(locale_len, return_value); if (locale_len == 0) { locale_str = intl_locale_get_default(); } locale = Locale::createFromName(locale_str); DATE_FORMAT_METHOD_FETCH_OBJECT_NO_CHECK; if (DATE_FORMAT_OBJECT(dfo) != NULL) { intl_errors_set(INTL_DATA_ERROR_P(dfo), U_ILLEGAL_ARGUMENT_ERROR, "datefmt_create: cannot call constructor twice", 0); return; } /* process calendar */ if (datefmt_process_calendar_arg(calendar_zv, locale, "datefmt_create", INTL_DATA_ERROR_P(dfo), calendar, calendar_type, calendar_owned) == FAILURE) { goto error; } /* process timezone */ explicit_tz = timezone_zv != NULL && Z_TYPE_P(timezone_zv) != IS_NULL; if (explicit_tz || calendar_owned ) { //we have an explicit time zone or a non-object calendar timezone = timezone_process_timezone_argument(timezone_zv, INTL_DATA_ERROR_P(dfo), "datefmt_create"); if (timezone == NULL) { goto error; } } /* Convert pattern (if specified) to UTF-16. */ if (pattern_str && pattern_str_len > 0) { intl_convert_utf8_to_utf16(&svalue, &slength, pattern_str, pattern_str_len, &INTL_DATA_ERROR_CODE(dfo)); if (U_FAILURE(INTL_DATA_ERROR_CODE(dfo))) { /* object construction -> only set global error */ intl_error_set(NULL, INTL_DATA_ERROR_CODE(dfo), "datefmt_create: " "error converting pattern to UTF-16", 0); goto error; } } if (pattern_str && pattern_str_len > 0) { DATE_FORMAT_OBJECT(dfo) = udat_open(UDAT_IGNORE, UDAT_IGNORE, locale_str, NULL, 0, svalue, slength, &INTL_DATA_ERROR_CODE(dfo)); } else { DATE_FORMAT_OBJECT(dfo) = udat_open((UDateFormatStyle)time_type, (UDateFormatStyle)date_type, locale_str, NULL, 0, svalue, slength, &INTL_DATA_ERROR_CODE(dfo)); } if (!U_FAILURE(INTL_DATA_ERROR_CODE(dfo))) { DateFormat *df = (DateFormat*)DATE_FORMAT_OBJECT(dfo); if (calendar_owned) { df->adoptCalendar(calendar); calendar_owned = false; } else { df->setCalendar(*calendar); } if (timezone != NULL) { df->adoptTimeZone(timezone); } } else { intl_error_set(NULL, INTL_DATA_ERROR_CODE(dfo), "datefmt_create: date " "formatter creation failed", 0); goto error; } /* Set the class variables */ dfo->date_type = date_type; dfo->time_type = time_type; dfo->calendar = calendar_type; dfo->requested_locale = estrdup(locale_str); error: if (svalue) { efree(svalue); } if (timezone != NULL && DATE_FORMAT_OBJECT(dfo) == NULL) { delete timezone; } if (calendar != NULL && calendar_owned) { delete calendar; } if (U_FAILURE(intl_error_get_code(NULL))) { /* free_object handles partially constructed instances fine */ Z_OBJ_P(return_value) = NULL; } }
/** * @bug 4056591 * Verify the function of the [s|g]et2DigitYearStart() API. */ void Test4056591() { int i; UCalendar *cal; UDateFormat *def; UDate start,exp,got; UChar s[10]; UChar *gotdate, *expdate; UChar pat[10]; UDate d[4]; UErrorCode status = U_ZERO_ERROR; const char* strings[] = { "091225", "091224", "611226", "991227" }; log_verbose("Testing s[get] 2 digit year start regressively\n"); cal=ucal_open(NULL, 0, "en_US", UCAL_GREGORIAN, &status); if(U_FAILURE(status)) { log_data_err("error in ucal_open caldef : %s - (Are you missing data?)\n", myErrorName(status)); return; } ucal_setDateTime(cal, 1809, UCAL_DECEMBER, 25, 17, 40, 30, &status); d[0]=ucal_getMillis(cal, &status); if(U_FAILURE(status)) { log_err("Error: failure in get millis: %s\n", myErrorName(status)); } ucal_setDateTime(cal, 1909, UCAL_DECEMBER, 24, 17, 40, 30, &status); d[1]=ucal_getMillis(cal, &status); ucal_setDateTime(cal, 1861, UCAL_DECEMBER, 26, 17, 40, 30, &status); d[2]=ucal_getMillis(cal, &status); ucal_setDateTime(cal, 1999, UCAL_DECEMBER, 27, 17, 40, 30, &status); d[3]=ucal_getMillis(cal, &status); u_uastrcpy(pat, "yyMMdd"); def = udat_open(UDAT_IGNORE,UDAT_IGNORE,NULL, NULL, 0, pat, u_strlen(pat), &status); if(U_FAILURE(status)) { log_err_status(status, "FAIL: error in creating the dateformat using u_openPattern(): %s\n", myErrorName(status)); return; } start = 1800; udat_set2DigitYearStart(def, start, &status); if(U_FAILURE(status)) log_err("ERROR: in setTwoDigitStartDate: %s\n", myErrorName(status)); if( (udat_get2DigitYearStart(def, &status) != start)) log_err("ERROR: get2DigitYearStart broken\n"); for(i = 0; i < 4; ++i) { u_uastrcpy(s, strings[i]); exp = d[i]; got = udat_parse(def, s, u_strlen(s), 0, &status); gotdate=myFormatit(def, got); expdate=myFormatit(def, exp); if (gotdate == NULL || expdate == NULL) { log_err("myFormatit failed!\n"); } else if(u_strcmp(gotdate, expdate) !=0) { log_err("set2DigitYearStart broken for %s \n got: %s, expected: %s\n", austrdup(s), austrdup(gotdate), austrdup(expdate) ); } } udat_close(def); ucal_close(cal); }
static void TestBuilder() { UErrorCode errorCode=U_ZERO_ERROR; UDateTimePatternGenerator *dtpg; UDateTimePatternConflict conflict; UEnumeration *en; UChar result[20]; int32_t length, pLength; const UChar *s, *p; const UChar* ptrResult[2]; int32_t count=0; UDateTimePatternGenerator *generator; int32_t formattedCapacity, resultLen,patternCapacity ; UChar pattern[40], formatted[40]; UDateFormat *formatter; UDate sampleDate = 837039928046.0; static const char locale[]= "fr"; UErrorCode status=U_ZERO_ERROR; /* test create an empty DateTimePatternGenerator */ dtpg=udatpg_openEmpty(&errorCode); if(U_FAILURE(errorCode)) { log_err("udatpg_openEmpty() failed - %s\n", u_errorName(errorCode)); return; } /* Add a pattern */ conflict = udatpg_addPattern(dtpg, redundantPattern, 5, FALSE, result, 20, &length, &errorCode); if(U_FAILURE(errorCode)) { log_err("udatpg_addPattern() failed - %s\n", u_errorName(errorCode)); return; } /* Add a redundant pattern */ conflict = udatpg_addPattern(dtpg, redundantPattern, 5, FALSE, result, 20, &length, &errorCode); if(conflict == UDATPG_NO_CONFLICT) { log_err("udatpg_addPattern() failed to find the duplicate pattern.\n"); return; } /* Test pattern == NULL */ s=NULL; length = udatpg_addPattern(dtpg, s, 0, FALSE, result, 20, &length, &errorCode); if(!U_FAILURE(errorCode)&&(length!=0) ) { log_err("udatpg_addPattern failed in illegal argument - pattern is NULL.\n"); return; } /* replace field type */ errorCode=U_ZERO_ERROR; conflict = udatpg_addPattern(dtpg, testPattern2, 7, FALSE, result, 20, &length, &errorCode); if((conflict != UDATPG_NO_CONFLICT)||U_FAILURE(errorCode)) { log_err("udatpg_addPattern() failed to add HH:mm v. - %s\n", u_errorName(errorCode)); return; } length = udatpg_replaceFieldTypes(dtpg, testPattern2, 7, replacedStr, 4, result, 20, &errorCode); if (U_FAILURE(errorCode) || (length==0) ) { log_err("udatpg_replaceFieldTypes failed!\n"); return; } /* Get all skeletons and the crroespong pattern for each skeleton. */ ptrResult[0] = testPattern2; ptrResult[1] = redundantPattern; count=0; en = udatpg_openSkeletons(dtpg, &errorCode); if (U_FAILURE(errorCode) || (length==0) ) { log_err("udatpg_openSkeletons failed!\n"); return; } while ( (s=uenum_unext(en, &length, &errorCode))!= NULL) { p = udatpg_getPatternForSkeleton(dtpg, s, length, &pLength); if (U_FAILURE(errorCode) || p==NULL || u_memcmp(p, ptrResult[count], pLength)!=0 ) { log_err("udatpg_getPatternForSkeleton failed!\n"); return; } count++; } uenum_close(en); /* Get all baseSkeletons */ en = udatpg_openBaseSkeletons(dtpg, &errorCode); count=0; while ( (s=uenum_unext(en, &length, &errorCode))!= NULL) { p = udatpg_getPatternForSkeleton(dtpg, s, length, &pLength); if (U_FAILURE(errorCode) || p==NULL || u_memcmp(p, resultBaseSkeletons[count], pLength)!=0 ) { log_err("udatpg_getPatternForSkeleton failed!\n"); return; } count++; } if (U_FAILURE(errorCode) || (length==0) ) { log_err("udatpg_openSkeletons failed!\n"); return; } uenum_close(en); udatpg_close(dtpg); /* sample code in Userguide */ patternCapacity = (int32_t)(sizeof(pattern)/sizeof((pattern)[0])); status=U_ZERO_ERROR; generator=udatpg_open(locale, &status); if(U_FAILURE(status)) { return; } /* get a pattern for an abbreviated month and day */ length = udatpg_getBestPattern(generator, skeleton, 4, pattern, patternCapacity, &status); formatter = udat_open(UDAT_IGNORE, UDAT_DEFAULT, locale, timeZoneGMT, -1, pattern, length, &status); if (formatter==NULL) { log_err("Failed to initialize the UDateFormat of the sample code in Userguide.\n"); udatpg_close(generator); return; } /* use it to format (or parse) */ formattedCapacity = (int32_t)(sizeof(formatted)/sizeof((formatted)[0])); resultLen=udat_format(formatter, ucal_getNow(), formatted, formattedCapacity, NULL, &status); /* for French, the result is "13 sept." */ /* cannot use the result from ucal_getNow() because the value change evreyday. */ resultLen=udat_format(formatter, sampleDate, formatted, formattedCapacity, NULL, &status); if ( u_memcmp(sampleFormatted, formatted, resultLen) != 0 ) { log_err("Failed udat_format() of sample code in Userguide.\n"); } udatpg_close(generator); udat_close(formatter); }
/** * @bug 4073003 */ void Test4073003() { int32_t pos,i; UDate d,dd; UChar *datestr; UChar temp[15]; UErrorCode status = U_ZERO_ERROR; UDateFormat *fmt; UChar *result, *result2; const char* tests [] = { "12/25/61", "12/25/1961", "4/3/1999", "4/3/99" }; fmt= udat_open(UDAT_SHORT,UDAT_SHORT ,NULL, NULL, 0, NULL, 0, &status); if(U_FAILURE(status)) { log_data_err("FAIL: error in creating the dateformat using short date and time style: %s (Are you missing data?)\n", myErrorName(status)); return; } u_uastrcpy(temp, "m/D/yy"); udat_applyPattern(fmt, FALSE, temp, u_strlen(temp)); for(i= 0; i < 4; i+=2) { status=U_ZERO_ERROR; datestr=(UChar*)malloc(sizeof(UChar) * (strlen(tests[i])+1)); u_uastrcpy(datestr, tests[i]); pos=0; d = udat_parse(fmt, datestr, u_strlen(datestr), &pos, &status); if(U_FAILURE(status)) { log_err("ERROR : in test 4073003: %s\n", myErrorName(status)); } free(datestr); datestr=(UChar*)malloc(sizeof(UChar) * (strlen(tests[i+1])+1)); u_uastrcpy(datestr, tests[i+1]); pos=0; status=U_ZERO_ERROR; dd = udat_parse(fmt, datestr, u_strlen(datestr), &pos, &status); if(U_FAILURE(status)) { log_err("ERROR : in test 4073003: %s\n", myErrorName(status)); } free(datestr); result =myFormatit(fmt, d); result2 =myFormatit(fmt, dd); if(!result || !result2) { log_data_err("Fail: could not format - exitting test\n"); return; } if (u_strcmp(result, result2)!=0) { log_err("Fail: %s != %s\n", austrdup(result), austrdup(result2) ); } else { log_verbose("Ok: %s == %s\n", austrdup(result), austrdup(result2) ); } } udat_close(fmt); }
static void TestRelativeCrash(void) { static const UChar tzName[] = { 0x0055, 0x0053, 0x002F, 0x0050, 0x0061, 0x0063, 0x0069, 0x0066, 0x0069, 0x0063, 0 }; static const UDate aDate = -631152000000.0; UErrorCode status = U_ZERO_ERROR; UErrorCode expectStatus = U_ILLEGAL_ARGUMENT_ERROR; UDateFormat icudf; icudf = udat_open(UDAT_NONE, UDAT_SHORT_RELATIVE, "en", tzName, -1, NULL, 0, &status); if ( U_SUCCESS(status) ) { const char *what = "???"; { UErrorCode subStatus = U_ZERO_ERROR; what = "udat_set2DigitYearStart"; log_verbose("Trying %s on a relative date..\n", what); udat_set2DigitYearStart(icudf, aDate, &subStatus); if(subStatus == expectStatus) { log_verbose("Success: did not crash on %s, but got %s.\n", what, u_errorName(subStatus)); } else { log_err("FAIL: didn't crash on %s, but got success %s instead of %s. \n", what, u_errorName(subStatus), u_errorName(expectStatus)); } } { /* clone works polymorphically. try it anyways */ UErrorCode subStatus = U_ZERO_ERROR; UDateFormat *oth; what = "clone"; log_verbose("Trying %s on a relative date..\n", what); oth = udat_clone(icudf, &subStatus); if(subStatus == U_ZERO_ERROR) { log_verbose("Success: did not crash on %s, but got %s.\n", what, u_errorName(subStatus)); udat_close(oth); /* ? */ } else { log_err("FAIL: didn't crash on %s, but got %s instead of %s. \n", what, u_errorName(subStatus), u_errorName(expectStatus)); } } { UErrorCode subStatus = U_ZERO_ERROR; what = "udat_get2DigitYearStart"; log_verbose("Trying %s on a relative date..\n", what); udat_get2DigitYearStart(icudf, &subStatus); if(subStatus == expectStatus) { log_verbose("Success: did not crash on %s, but got %s.\n", what, u_errorName(subStatus)); } else { log_err("FAIL: didn't crash on %s, but got success %s instead of %s. \n", what, u_errorName(subStatus), u_errorName(expectStatus)); } } { /* Now udat_toPattern works for relative date formatters, unless localized is TRUE */ UErrorCode subStatus = U_ZERO_ERROR; what = "udat_toPattern"; log_verbose("Trying %s on a relative date..\n", what); udat_toPattern(icudf, TRUE,NULL,0, &subStatus); if(subStatus == expectStatus) { log_verbose("Success: did not crash on %s, but got %s.\n", what, u_errorName(subStatus)); } else { log_err("FAIL: didn't crash on %s, but got success %s instead of %s. \n", what, u_errorName(subStatus), u_errorName(expectStatus)); } } { UErrorCode subStatus = U_ZERO_ERROR; what = "udat_applyPattern"; log_verbose("Trying %s on a relative date..\n", what); udat_applyPattern(icudf, FALSE,tzName,-1); subStatus = U_ILLEGAL_ARGUMENT_ERROR; /* what it should be, if this took an errorcode. */ if(subStatus == expectStatus) { log_verbose("Success: did not crash on %s, but got %s.\n", what, u_errorName(subStatus)); } else { log_err("FAIL: didn't crash on %s, but got success %s instead of %s. \n", what, u_errorName(subStatus), u_errorName(expectStatus)); } } { UErrorCode subStatus = U_ZERO_ERROR; what = "udat_getSymbols"; log_verbose("Trying %s on a relative date..\n", what); udat_getSymbols(icudf, UDAT_ERAS,0,NULL,0, &subStatus); /* bogus values */ if(subStatus == expectStatus) { log_verbose("Success: did not crash on %s, but got %s.\n", what, u_errorName(subStatus)); } else { log_err("FAIL: didn't crash on %s, but got success %s instead of %s. \n", what, u_errorName(subStatus), u_errorName(expectStatus)); } } { UErrorCode subStatus = U_ZERO_ERROR; what = "udat_countSymbols"; log_verbose("Trying %s on a relative date..\n", what); udat_countSymbols(icudf, UDAT_ERAS); subStatus = U_ILLEGAL_ARGUMENT_ERROR; /* should have an errorcode. */ if(subStatus == expectStatus) { log_verbose("Success: did not crash on %s, but got %s.\n", what, u_errorName(subStatus)); } else { log_err("FAIL: didn't crash on %s, but got success %s instead of %s. \n", what, u_errorName(subStatus), u_errorName(expectStatus)); } } udat_close(icudf); } else { log_data_err("FAIL: err calling udat_open() ->%s (Are you missing data?)\n", u_errorName(status)); } }
/** * @bug 4029195 */ void Test4029195() { int32_t resultlength, resultlengthneeded; UChar *fmdt, *todayS, *rt; UChar *pat=NULL; UChar *temp; UDate today, d1; UDateFormat *df; int32_t parsepos; UErrorCode status = U_ZERO_ERROR; log_verbose("Testing date format and parse function in regression test\n"); today = ucal_getNow(); df = udat_open(UDAT_DEFAULT,UDAT_DEFAULT ,"en_US", NULL, 0, NULL, 0, &status); if(U_FAILURE(status)) { log_data_err("FAIL: error in creating the dateformat using default date and time style : %s (Are you missing data?)\n", myErrorName(status)); return; } resultlength=0; resultlengthneeded=udat_toPattern(df, TRUE, NULL, resultlength, &status); if(status==U_BUFFER_OVERFLOW_ERROR) { status=U_ZERO_ERROR; resultlength=resultlengthneeded + 1; pat=(UChar*)malloc(sizeof(UChar) * resultlength); udat_toPattern(df, TRUE, pat, resultlength, &status); } log_verbose("pattern: %s\n", austrdup(pat)); fmdt = myFormatit(df, today); if(fmdt) { log_verbose("today: %s\n", austrdup(fmdt)); } else { log_data_err("ERROR: couldn't format, exitting test"); return; } temp=(UChar*)malloc(sizeof(UChar) * 10); u_uastrcpy(temp, "M yyyy dd"); udat_applyPattern(df, TRUE, temp, u_strlen(temp)); todayS =myFormatit(df, today); log_verbose("After teh pattern is applied\n today: %s\n", austrdup(todayS) ); parsepos=0; d1=udat_parse(df, todayS, u_strlen(todayS), &parsepos, &status); if(U_FAILURE(status)) { log_err("FAIL: Error in parsing using udat_parse(.....): %s\n", myErrorName(status)); } rt =myFormatit(df, d1); log_verbose("today: %s\n", austrdup(rt) ); log_verbose("round trip: %s\n", austrdup(rt) ); if(u_strcmp(rt, todayS)!=0) { log_err("Fail: Want %s Got %s\n", austrdup(todayS), austrdup(rt) ); } else log_verbose("Pass: parse and format working fine\n"); udat_close(df); free(temp); if(pat != NULL) { free(pat); } }
/* Testing the DateFormat API */ static void TestDateFormat() { UDateFormat *def, *fr, *it, *de, *def1, *fr_pat; UDateFormat *any; UDateFormat *copy; UErrorCode status = U_ZERO_ERROR; UChar* result = NULL; const UCalendar *cal; const UNumberFormat *numformat1, *numformat2; UChar temp[50]; int32_t numlocales; UDate d1; int i; int32_t resultlength; int32_t resultlengthneeded; int32_t parsepos; UDate d = 837039928046.0; double num = -10456.37; /*const char* str="yyyy.MM.dd G 'at' hh:mm:ss z"; const char t[]="2/3/76 2:50 AM";*/ /*Testing udat_open() to open a dateformat */ ctest_setTimeZone(NULL, &status); log_verbose("\nTesting udat_open() with various parameters\n"); fr = udat_open(UDAT_FULL, UDAT_DEFAULT, "fr_FR", NULL,0, NULL, 0,&status); if(U_FAILURE(status)) { log_data_err("FAIL: error in creating the dateformat using full time style with french locale -> %s (Are you missing data?)\n", myErrorName(status) ); return; } /* this is supposed to open default date format, but later on it treats it like it is "en_US" - very bad if you try to run the tests on machine where default locale is NOT "en_US" */ /* def = udat_open(UDAT_SHORT, UDAT_SHORT, NULL, NULL, 0, &status); */ def = udat_open(UDAT_SHORT, UDAT_SHORT, "en_US", NULL, 0,NULL, 0, &status); if(U_FAILURE(status)) { log_err("FAIL: error in creating the dateformat using short date and time style\n %s\n", myErrorName(status) ); return; } it = udat_open(UDAT_DEFAULT, UDAT_MEDIUM, "it_IT", NULL, 0, NULL, 0,&status); if(U_FAILURE(status)) { log_err("FAIL: error in creating the dateformat using medium date style with italian locale\n %s\n", myErrorName(status) ); return; } de = udat_open(UDAT_LONG, UDAT_LONG, "de_DE", NULL, 0, NULL, 0,&status); if(U_FAILURE(status)) { log_err("FAIL: error in creating the dateformat using long time and date styles with german locale\n %s\n", myErrorName(status)); return; } /*creating a default dateformat */ def1 = udat_open(UDAT_SHORT, UDAT_SHORT, NULL, NULL, 0,NULL, 0, &status); if(U_FAILURE(status)) { log_err("FAIL: error in creating the dateformat using short date and time style\n %s\n", myErrorName(status) ); return; } /*Testing udat_getAvailable() and udat_countAvailable()*/ log_verbose("\nTesting getAvailableLocales and countAvailable()\n"); numlocales=udat_countAvailable(); /* use something sensible w/o hardcoding the count */ if(numlocales < 0) log_data_err("FAIL: error in countAvailable\n"); log_verbose("The number of locales for which date/time formatting patterns are available is %d\n", numlocales); for(i=0;i<numlocales;i++) { UErrorCode subStatus = U_ZERO_ERROR; log_verbose("Testing open of %s\n", udat_getAvailable(i)); any = udat_open(UDAT_SHORT, UDAT_SHORT, udat_getAvailable(i), NULL ,0, NULL, 0, &subStatus); if(U_FAILURE(subStatus)) { log_data_err("FAIL: date format %s (getAvailable(%d)) is not instantiable: %s\n", udat_getAvailable(i), i, u_errorName(subStatus)); } udat_close(any); } /*Testing udat_clone()*/ log_verbose("\nTesting the udat_clone() function of date format\n"); copy=udat_clone(def, &status); if(U_FAILURE(status)){ log_err("Error in creating the clone using udat_clone: %s\n", myErrorName(status) ); } /*if(def != copy) log_err("Error in udat_clone");*/ /*how should i check for equality???? */ /*Testing udat_format()*/ log_verbose("\nTesting the udat_format() function of date format\n"); u_uastrcpy(temp, "7/10/96 4:05 PM"); /*format using def */ resultlength=0; resultlengthneeded=udat_format(def, d, NULL, resultlength, NULL, &status); if(status==U_BUFFER_OVERFLOW_ERROR) { status=U_ZERO_ERROR; resultlength=resultlengthneeded+1; if(result != NULL) { free(result); result = NULL; } result=(UChar*)malloc(sizeof(UChar) * resultlength); udat_format(def, d, result, resultlength, NULL, &status); } if(U_FAILURE(status) || !result) { log_err("FAIL: Error in formatting using udat_format(.....) %s\n", myErrorName(status) ); return; } else log_verbose("PASS: formatting successful\n"); if(u_strcmp(result, temp)==0) log_verbose("PASS: Date Format for US locale successful using udat_format()\n"); else { char xbuf[2048]; char gbuf[2048]; u_austrcpy(xbuf, temp); u_austrcpy(gbuf, result); log_err("FAIL: Date Format for US locale failed using udat_format() - expected %s got %s\n", xbuf, gbuf); } /*format using fr */ u_unescape("10 juil. 1996 16:05:28 heure avanc\\u00E9e du Pacifique", temp, 50); if(result != NULL) { free(result); result = NULL; } result=myDateFormat(fr, d); if(u_strcmp(result, temp)==0) log_verbose("PASS: Date Format for french locale successful using udat_format()\n"); else log_data_err("FAIL: Date Format for french locale failed using udat_format().\n" ); /*format using it */ u_uastrcpy(temp, "10/lug/1996 16:05:28"); { UChar *fmtted; char g[100]; char x[100]; fmtted = myDateFormat(it,d); u_austrcpy(g, fmtted); u_austrcpy(x, temp); if(u_strcmp(fmtted, temp)==0) { log_verbose("PASS: Date Format for italian locale successful uisng udat_format() - wanted %s, got %s\n", x, g); } else { log_data_err("FAIL: Date Format for italian locale failed using udat_format() - wanted %s, got %s\n", x, g); } } /*Testing parsing using udat_parse()*/ log_verbose("\nTesting parsing using udat_parse()\n"); u_uastrcpy(temp,"2/3/76 2:50 AM"); parsepos=0; status=U_ZERO_ERROR; d1=udat_parse(def, temp, u_strlen(temp), &parsepos, &status); if(U_FAILURE(status)) { log_err("FAIL: Error in parsing using udat_parse(.....) %s\n", myErrorName(status) ); } else log_verbose("PASS: parsing succesful\n"); /*format it back and check for equality */ if(u_strcmp(myDateFormat(def, d1),temp)!=0) log_err("FAIL: error in parsing\n"); /*Testing parsing using udat_parse()*/ log_verbose("\nTesting parsing using udat_parse()\n"); u_uastrcpy(temp,"2/Don't parse this part"); status=U_ZERO_ERROR; d1=udat_parse(def, temp, u_strlen(temp), NULL, &status); if(status != U_PARSE_ERROR) { log_err("FAIL: udat_parse(\"bad string\") passed when it should have failed\n"); } else log_verbose("PASS: parsing succesful\n"); /*Testing udat_openPattern() */ status=U_ZERO_ERROR; log_verbose("\nTesting the udat_openPattern with a specified pattern\n"); /*for french locale */ fr_pat=udat_open(UDAT_IGNORE, UDAT_IGNORE,"fr_FR",NULL,0,temp, u_strlen(temp), &status); if(U_FAILURE(status)) { log_err("FAIL: Error in creating a date format using udat_openPattern \n %s\n", myErrorName(status) ); } else log_verbose("PASS: creating dateformat using udat_openPattern() succesful\n"); /*Testing applyPattern and toPattern */ log_verbose("\nTesting applyPattern and toPattern()\n"); udat_applyPattern(def1, FALSE, temp, u_strlen(temp)); log_verbose("Extracting the pattern\n"); resultlength=0; resultlengthneeded=udat_toPattern(def1, FALSE, NULL, resultlength, &status); if(status==U_BUFFER_OVERFLOW_ERROR) { status=U_ZERO_ERROR; resultlength=resultlengthneeded + 1; result=(UChar*)malloc(sizeof(UChar) * resultlength); udat_toPattern(def1, FALSE, result, resultlength, &status); } if(U_FAILURE(status)) { log_err("FAIL: error in extracting the pattern from UNumberFormat\n %s\n", myErrorName(status) ); } if(u_strcmp(result, temp)!=0) log_err("FAIL: Error in extracting the pattern\n"); else log_verbose("PASS: applyPattern and toPattern work fine\n"); if(result != NULL) { free(result); result = NULL; } /*Testing getter and setter functions*/ /*isLenient and setLenient()*/ log_verbose("\nTesting the isLenient and setLenient properties\n"); udat_setLenient(fr, udat_isLenient(it)); if(udat_isLenient(fr) != udat_isLenient(it)) log_err("ERROR: setLenient() failed\n"); else log_verbose("PASS: setLenient() successful\n"); /*Test get2DigitYearStart set2DigitYearStart */ log_verbose("\nTesting the get and set 2DigitYearStart properties\n"); d1= udat_get2DigitYearStart(fr_pat,&status); if(U_FAILURE(status)) { log_err("ERROR: udat_get2DigitYearStart failed %s\n", myErrorName(status) ); } status = U_ZERO_ERROR; udat_set2DigitYearStart(def1 ,d1, &status); if(U_FAILURE(status)) { log_err("ERROR: udat_set2DigitYearStart failed %s\n", myErrorName(status) ); } if(udat_get2DigitYearStart(fr_pat, &status) != udat_get2DigitYearStart(def1, &status)) log_err("FAIL: error in set2DigitYearStart\n"); else log_verbose("PASS: set2DigitYearStart successful\n"); /*try setting it to another value */ udat_set2DigitYearStart(de, 2000.0, &status); if(U_FAILURE(status)){ log_verbose("ERROR: udat_set2DigitYearStart failed %s\n", myErrorName(status) ); } if(udat_get2DigitYearStart(de, &status) != 2000) log_err("FAIL: error in set2DigitYearStart\n"); else log_verbose("PASS: set2DigitYearStart successful\n"); /*Test getNumberFormat() and setNumberFormat() */ log_verbose("\nTesting the get and set NumberFormat properties of date format\n"); numformat1=udat_getNumberFormat(fr_pat); udat_setNumberFormat(def1, numformat1); numformat2=udat_getNumberFormat(def1); if(u_strcmp(myNumformat(numformat1, num), myNumformat(numformat2, num)) !=0) log_err("FAIL: error in setNumberFormat or getNumberFormat()\n"); else log_verbose("PASS:setNumberFormat and getNumberFormat succesful\n"); /*try setting the number format to another format */ numformat1=udat_getNumberFormat(def); udat_setNumberFormat(def1, numformat1); numformat2=udat_getNumberFormat(def1); if(u_strcmp(myNumformat(numformat1, num), myNumformat(numformat2, num)) !=0) log_err("FAIL: error in setNumberFormat or getNumberFormat()\n"); else log_verbose("PASS: setNumberFormat and getNumberFormat succesful\n"); /*Test getCalendar and setCalendar*/ log_verbose("\nTesting the udat_getCalendar() and udat_setCalendar() properties\n"); cal=udat_getCalendar(fr_pat); udat_setCalendar(def1, cal); if(!ucal_equivalentTo(udat_getCalendar(fr_pat), udat_getCalendar(def1))) log_err("FAIL: Error in setting and getting the calendar\n"); else log_verbose("PASS: getting and setting calendar successful\n"); if(result!=NULL) { free(result); } /*Closing the UDateForamt */ udat_close(def); udat_close(fr); udat_close(it); udat_close(de); udat_close(def1); udat_close(fr_pat); udat_close(copy); ctest_resetTimeZone(); }
void IntlDateTimeFormat::initializeDateTimeFormat(ExecState& exec, JSValue locales, JSValue originalOptions) { VM& vm = exec.vm(); auto scope = DECLARE_THROW_SCOPE(vm); // 12.1.1 InitializeDateTimeFormat (dateTimeFormat, locales, options) (ECMA-402 2.0) // 1. If dateTimeFormat.[[initializedIntlObject]] is true, throw a TypeError exception. // 2. Set dateTimeFormat.[[initializedIntlObject]] to true. // 3. Let requestedLocales be CanonicalizeLocaleList(locales). Vector<String> requestedLocales = canonicalizeLocaleList(exec, locales); // 4. ReturnIfAbrupt(requestedLocales), RETURN_IF_EXCEPTION(scope, void()); // 5. Let options be ToDateTimeOptions(options, "any", "date"). JSObject* options = toDateTimeOptionsAnyDate(exec, originalOptions); // 6. ReturnIfAbrupt(options). RETURN_IF_EXCEPTION(scope, void()); // 7. Let opt be a new Record. HashMap<String, String> localeOpt; // 8. Let matcher be GetOption(options, "localeMatcher", "string", «"lookup", "best fit"», "best fit"). String localeMatcher = intlStringOption(exec, options, vm.propertyNames->localeMatcher, { "lookup", "best fit" }, "localeMatcher must be either \"lookup\" or \"best fit\"", "best fit"); // 9. ReturnIfAbrupt(matcher). RETURN_IF_EXCEPTION(scope, void()); // 10. Set opt.[[localeMatcher]] to matcher. localeOpt.add(vm.propertyNames->localeMatcher.string(), localeMatcher); // 11. Let localeData be the value of %DateTimeFormat%.[[localeData]]. // 12. Let r be ResolveLocale( %DateTimeFormat%.[[availableLocales]], requestedLocales, opt, %DateTimeFormat%.[[relevantExtensionKeys]], localeData). const HashSet<String> availableLocales = exec.jsCallee()->globalObject()->intlDateTimeFormatAvailableLocales(); HashMap<String, String> resolved = resolveLocale(exec, availableLocales, requestedLocales, localeOpt, relevantExtensionKeys, WTF_ARRAY_LENGTH(relevantExtensionKeys), localeData); // 13. Set dateTimeFormat.[[locale]] to the value of r.[[locale]]. m_locale = resolved.get(vm.propertyNames->locale.string()); if (m_locale.isEmpty()) { throwTypeError(&exec, scope, ASCIILiteral("failed to initialize DateTimeFormat due to invalid locale")); return; } // 14. Set dateTimeFormat.[[calendar]] to the value of r.[[ca]]. m_calendar = resolved.get(ASCIILiteral("ca")); // Switch to preferred aliases. if (m_calendar == "gregory") m_calendar = ASCIILiteral("gregorian"); else if (m_calendar == "islamicc") m_calendar = ASCIILiteral("islamic-civil"); else if (m_calendar == "ethioaa") m_calendar = ASCIILiteral("ethiopic-amete-alem"); // 15. Set dateTimeFormat.[[numberingSystem]] to the value of r.[[nu]]. m_numberingSystem = resolved.get(ASCIILiteral("nu")); // 16. Let dataLocale be the value of r.[[dataLocale]]. String dataLocale = resolved.get(ASCIILiteral("dataLocale")); // 17. Let tz be Get(options, "timeZone"). JSValue tzValue = options->get(&exec, vm.propertyNames->timeZone); // 18. ReturnIfAbrupt(tz). RETURN_IF_EXCEPTION(scope, void()); // 19. If tz is not undefined, then String tz; if (!tzValue.isUndefined()) { // a. Let tz be ToString(tz). String originalTz = tzValue.toWTFString(&exec); // b. ReturnIfAbrupt(tz). RETURN_IF_EXCEPTION(scope, void()); // c. If the result of IsValidTimeZoneName(tz) is false, then i. Throw a RangeError exception. // d. Let tz be CanonicalizeTimeZoneName(tz). tz = canonicalizeTimeZoneName(originalTz); if (tz.isNull()) { throwRangeError(&exec, scope, String::format("invalid time zone: %s", originalTz.utf8().data())); return; } } else { // 20. Else, // a. Let tz be DefaultTimeZone(). tz = defaultTimeZone(); } // 21. Set dateTimeFormat.[[timeZone]] to tz. m_timeZone = tz; // 22. Let opt be a new Record. // Rather than building a record, build the skeleton pattern. StringBuilder skeletonBuilder; // 23. For each row of Table 3, except the header row, do: // a. Let prop be the name given in the Property column of the row. // b. Let value be GetOption(options, prop, "string", «the strings given in the Values column of the row», undefined). // c. ReturnIfAbrupt(value). // d. Set opt.[[<prop>]] to value. auto narrowShortLong = { "narrow", "short", "long" }; auto twoDigitNumeric = { "2-digit", "numeric" }; auto twoDigitNumericNarrowShortLong = { "2-digit", "numeric", "narrow", "short", "long" }; auto shortLong = { "short", "long" }; String weekday = intlStringOption(exec, options, vm.propertyNames->weekday, narrowShortLong, "weekday must be \"narrow\", \"short\", or \"long\"", nullptr); RETURN_IF_EXCEPTION(scope, void()); if (!weekday.isNull()) { if (weekday == "narrow") skeletonBuilder.appendLiteral("EEEEE"); else if (weekday == "short") skeletonBuilder.appendLiteral("EEE"); else if (weekday == "long") skeletonBuilder.appendLiteral("EEEE"); } String era = intlStringOption(exec, options, vm.propertyNames->era, narrowShortLong, "era must be \"narrow\", \"short\", or \"long\"", nullptr); RETURN_IF_EXCEPTION(scope, void()); if (!era.isNull()) { if (era == "narrow") skeletonBuilder.appendLiteral("GGGGG"); else if (era == "short") skeletonBuilder.appendLiteral("GGG"); else if (era == "long") skeletonBuilder.appendLiteral("GGGG"); } String year = intlStringOption(exec, options, vm.propertyNames->year, twoDigitNumeric, "year must be \"2-digit\" or \"numeric\"", nullptr); RETURN_IF_EXCEPTION(scope, void()); if (!year.isNull()) { if (year == "2-digit") skeletonBuilder.appendLiteral("yy"); else if (year == "numeric") skeletonBuilder.append('y'); } String month = intlStringOption(exec, options, vm.propertyNames->month, twoDigitNumericNarrowShortLong, "month must be \"2-digit\", \"numeric\", \"narrow\", \"short\", or \"long\"", nullptr); RETURN_IF_EXCEPTION(scope, void()); if (!month.isNull()) { if (month == "2-digit") skeletonBuilder.appendLiteral("MM"); else if (month == "numeric") skeletonBuilder.append('M'); else if (month == "narrow") skeletonBuilder.appendLiteral("MMMMM"); else if (month == "short") skeletonBuilder.appendLiteral("MMM"); else if (month == "long") skeletonBuilder.appendLiteral("MMMM"); } String day = intlStringOption(exec, options, vm.propertyNames->day, twoDigitNumeric, "day must be \"2-digit\" or \"numeric\"", nullptr); RETURN_IF_EXCEPTION(scope, void()); if (!day.isNull()) { if (day == "2-digit") skeletonBuilder.appendLiteral("dd"); else if (day == "numeric") skeletonBuilder.append('d'); } String hour = intlStringOption(exec, options, vm.propertyNames->hour, twoDigitNumeric, "hour must be \"2-digit\" or \"numeric\"", nullptr); RETURN_IF_EXCEPTION(scope, void()); // We need hour12 to make the hour skeleton pattern decision, so do this early. // 32. Let hr12 be GetOption(options, "hour12", "boolean", undefined, undefined). bool isHour12Undefined; bool hr12 = intlBooleanOption(exec, options, vm.propertyNames->hour12, isHour12Undefined); // 33. ReturnIfAbrupt(hr12). RETURN_IF_EXCEPTION(scope, void()); if (!hour.isNull()) { if (isHour12Undefined) { if (hour == "2-digit") skeletonBuilder.appendLiteral("jj"); else if (hour == "numeric") skeletonBuilder.append('j'); } else if (hr12) { if (hour == "2-digit") skeletonBuilder.appendLiteral("hh"); else if (hour == "numeric") skeletonBuilder.append('h'); } else { if (hour == "2-digit") skeletonBuilder.appendLiteral("HH"); else if (hour == "numeric") skeletonBuilder.append('H'); } } String minute = intlStringOption(exec, options, vm.propertyNames->minute, twoDigitNumeric, "minute must be \"2-digit\" or \"numeric\"", nullptr); RETURN_IF_EXCEPTION(scope, void()); if (!minute.isNull()) { if (minute == "2-digit") skeletonBuilder.appendLiteral("mm"); else if (minute == "numeric") skeletonBuilder.append('m'); } String second = intlStringOption(exec, options, vm.propertyNames->second, twoDigitNumeric, "second must be \"2-digit\" or \"numeric\"", nullptr); RETURN_IF_EXCEPTION(scope, void()); if (!second.isNull()) { if (second == "2-digit") skeletonBuilder.appendLiteral("ss"); else if (second == "numeric") skeletonBuilder.append('s'); } String timeZoneName = intlStringOption(exec, options, vm.propertyNames->timeZoneName, shortLong, "timeZoneName must be \"short\" or \"long\"", nullptr); RETURN_IF_EXCEPTION(scope, void()); if (!timeZoneName.isNull()) { if (timeZoneName == "short") skeletonBuilder.append('z'); else if (timeZoneName == "long") skeletonBuilder.appendLiteral("zzzz"); } // 24. Let dataLocaleData be Get(localeData, dataLocale). // 25. Let formats be Get(dataLocaleData, "formats"). // 26. Let matcher be GetOption(options, "formatMatcher", "string", «"basic", "best fit"», "best fit"). intlStringOption(exec, options, vm.propertyNames->formatMatcher, { "basic", "best fit" }, "formatMatcher must be either \"basic\" or \"best fit\"", "best fit"); // 27. ReturnIfAbrupt(matcher). RETURN_IF_EXCEPTION(scope, void()); // Always use ICU date format generator, rather than our own pattern list and matcher. // Covers steps 28-36. UErrorCode status = U_ZERO_ERROR; UDateTimePatternGenerator* generator = udatpg_open(dataLocale.utf8().data(), &status); if (U_FAILURE(status)) { throwTypeError(&exec, scope, ASCIILiteral("failed to initialize DateTimeFormat")); return; } String skeleton = skeletonBuilder.toString(); StringView skeletonView(skeleton); Vector<UChar, 32> patternBuffer(32); status = U_ZERO_ERROR; auto patternLength = udatpg_getBestPattern(generator, skeletonView.upconvertedCharacters(), skeletonView.length(), patternBuffer.data(), patternBuffer.size(), &status); if (status == U_BUFFER_OVERFLOW_ERROR) { status = U_ZERO_ERROR; patternBuffer.grow(patternLength); udatpg_getBestPattern(generator, skeletonView.upconvertedCharacters(), skeletonView.length(), patternBuffer.data(), patternLength, &status); } udatpg_close(generator); if (U_FAILURE(status)) { throwTypeError(&exec, scope, ASCIILiteral("failed to initialize DateTimeFormat")); return; } StringView pattern(patternBuffer.data(), patternLength); setFormatsFromPattern(pattern); status = U_ZERO_ERROR; StringView timeZoneView(m_timeZone); m_dateFormat = std::unique_ptr<UDateFormat, UDateFormatDeleter>(udat_open(UDAT_PATTERN, UDAT_PATTERN, m_locale.utf8().data(), timeZoneView.upconvertedCharacters(), timeZoneView.length(), pattern.upconvertedCharacters(), pattern.length(), &status)); if (U_FAILURE(status)) { throwTypeError(&exec, scope, ASCIILiteral("failed to initialize DateTimeFormat")); return; } // 37. Set dateTimeFormat.[[boundFormat]] to undefined. // Already undefined. // 38. Set dateTimeFormat.[[initializedDateTimeFormat]] to true. m_initializedDateTimeFormat = true; // 39. Return dateTimeFormat. }
static void TestDateFormatCalendar() { UDateFormat *date=0, *time=0, *full=0; UCalendar *cal=0; UChar buf[256]; char cbuf[256]; int32_t pos; UDate when; UErrorCode ec = U_ZERO_ERROR; ctest_setTimeZone(NULL, &ec); /* Create a formatter for date fields. */ date = udat_open(UDAT_NONE, UDAT_SHORT, "en_US", NULL, 0, NULL, 0, &ec); if (U_FAILURE(ec)) { log_data_err("FAIL: udat_open(NONE, SHORT, en_US) failed with %s (Are you missing data?)\n", u_errorName(ec)); goto FAIL; } /* Create a formatter for time fields. */ time = udat_open(UDAT_SHORT, UDAT_NONE, "en_US", NULL, 0, NULL, 0, &ec); if (U_FAILURE(ec)) { log_err("FAIL: udat_open(SHORT, NONE, en_US) failed with %s\n", u_errorName(ec)); goto FAIL; } /* Create a full format for output */ full = udat_open(UDAT_FULL, UDAT_FULL, "en_US", NULL, 0, NULL, 0, &ec); if (U_FAILURE(ec)) { log_err("FAIL: udat_open(FULL, FULL, en_US) failed with %s\n", u_errorName(ec)); goto FAIL; } /* Create a calendar */ cal = ucal_open(NULL, 0, "en_US", UCAL_GREGORIAN, &ec); if (U_FAILURE(ec)) { log_err("FAIL: ucal_open(en_US) failed with %s\n", u_errorName(ec)); goto FAIL; } /* Parse the date */ ucal_clear(cal); u_uastrcpy(buf, "4/5/2001"); pos = 0; udat_parseCalendar(date, cal, buf, -1, &pos, &ec); if (U_FAILURE(ec)) { log_err("FAIL: udat_parseCalendar(4/5/2001) failed at %d with %s\n", pos, u_errorName(ec)); goto FAIL; } /* Parse the time */ u_uastrcpy(buf, "5:45 PM"); pos = 0; udat_parseCalendar(time, cal, buf, -1, &pos, &ec); if (U_FAILURE(ec)) { log_err("FAIL: udat_parseCalendar(17:45) failed at %d with %s\n", pos, u_errorName(ec)); goto FAIL; } /* Check result */ when = ucal_getMillis(cal, &ec); if (U_FAILURE(ec)) { log_err("FAIL: ucal_getMillis() failed with %s\n", u_errorName(ec)); goto FAIL; } udat_format(full, when, buf, sizeof(buf), NULL, &ec); if (U_FAILURE(ec)) { log_err("FAIL: udat_format() failed with %s\n", u_errorName(ec)); goto FAIL; } u_austrcpy(cbuf, buf); /* Thursday, April 5, 2001 5:45:00 PM PDT 986517900000 */ if (when == 986517900000.0) { log_verbose("Ok: Parsed result: %s\n", cbuf); } else { log_err("FAIL: Parsed result: %s, exp 4/5/2001 5:45 PM\n", cbuf); } FAIL: udat_close(date); udat_close(time); udat_close(full); ucal_close(cal); ctest_resetTimeZone(); }
/* Print out a calendar for c's current month */ static void print_month(UCalendar *c, UChar *days [], UBool useLongNames, int32_t fdow, UErrorCode *status) { int32_t width, pad, i, day; int32_t lens [DAY_COUNT]; int32_t firstday, current; UNumberFormat *nfmt; UDateFormat *dfmt; UChar s [BUF_SIZE]; const UChar *pat = (useLongNames ? sLongPat : sShortPat); int32_t len = (useLongNames ? 9 : 8); if(U_FAILURE(*status)) return; /* ========== Generate the header containing the month and year */ /* Open a formatter with a month and year only pattern */ dfmt = udat_open(UDAT_IGNORE,UDAT_IGNORE,NULL,NULL,0,pat, len,status); /* Format the date */ udat_format(dfmt, ucal_getMillis(c, status), s, BUF_SIZE, 0, status); /* ========== Get the day names */ get_days(dfmt, days, useLongNames, fdow, status); /* ========== Print the header */ /* Calculate widths for justification */ width = 6; /* 6 spaces, 1 between each day name */ for(i = 0; i < DAY_COUNT; ++i) { lens[i] = u_strlen(days[i]); width += lens[i]; } /* Print the header, centered among the day names */ pad = width - u_strlen(s); indent(pad / 2, stdout); uprint(s, stdout, status); putc('\n', stdout); /* ========== Print the day names */ print_days(days, stdout, status); putc('\n', stdout); /* ========== Print the calendar */ /* Get the first of the month */ ucal_set(c, UCAL_DATE, 1); firstday = ucal_get(c, UCAL_DAY_OF_WEEK, status); /* The day of the week for the first day of the month is based on 1-based days of the week, which were also reordered when placed in the days array. Account for this here by offsetting by the first day of the week for the locale, which is also 1-based. */ firstday -= fdow; /* Open the formatter */ nfmt = unum_open(UNUM_DECIMAL, NULL,0,NULL,NULL, status); /* Indent the correct number of spaces for the first week */ current = firstday; if(current < 0) { current += 7; } for(i = 0; i < current; ++i) indent(lens[i] + 1, stdout); /* Finally, print out the days */ day = ucal_get(c, UCAL_DATE, status); do { /* Format the current day string */ unum_format(nfmt, day, s, BUF_SIZE, 0, status); /* Calculate the justification and indent */ pad = lens[current] - u_strlen(s); indent(pad, stdout); /* Print the day number out, followed by a space */ uprint(s, stdout, status); putc(' ', stdout); /* Update the current day */ ++current; current %= DAY_COUNT; /* If we're at day 0 (first day of the week), insert a newline */ if(current == 0) { putc('\n', stdout); } /* Go to the next day */ ucal_add(c, UCAL_DATE, 1, status); day = ucal_get(c, UCAL_DATE, status); } while(day != 1); /* Output a trailing newline */ putc('\n', stdout); /* Clean up */ free_days(days); unum_close(nfmt); udat_close(dfmt); }