示例#1
0
CF_PRIVATE UCalendar *__CFCalendarCreateUCalendar(CFStringRef calendarID, CFStringRef localeID, CFTimeZoneRef tz) {
    if (calendarID) {
	CFDictionaryRef components = CFLocaleCreateComponentsFromLocaleIdentifier(kCFAllocatorSystemDefault, localeID);
	CFMutableDictionaryRef mcomponents = CFDictionaryCreateMutableCopy(kCFAllocatorSystemDefault, 0, components);
	CFDictionarySetValue(mcomponents, kCFLocaleCalendarIdentifier, calendarID);
	localeID = CFLocaleCreateLocaleIdentifierFromComponents(kCFAllocatorSystemDefault, mcomponents);
	CFRelease(mcomponents);
	CFRelease(components);
    }

    char buffer[BUFFER_SIZE];
    const char *cstr = CFStringGetCStringPtr(localeID, kCFStringEncodingASCII);
    if (NULL == cstr) {
	if (CFStringGetCString(localeID, buffer, BUFFER_SIZE, kCFStringEncodingASCII)) cstr = buffer;
    }
    if (NULL == cstr) {
	if (calendarID) CFRelease(localeID);
	return NULL;
    }
    
    UChar ubuffer[BUFFER_SIZE];
    CFStringRef tznam = CFTimeZoneGetName(tz);
    CFIndex cnt = CFStringGetLength(tznam);
    if (BUFFER_SIZE < cnt) cnt = BUFFER_SIZE;
    CFStringGetCharacters(tznam, CFRangeMake(0, cnt), (UniChar *)ubuffer);

    UErrorCode status = U_ZERO_ERROR;
    UCalendar *cal = ucal_open(ubuffer, cnt, cstr, UCAL_DEFAULT, &status);
    if (calendarID) CFRelease(localeID);
    return cal;
}
示例#2
0
RSPrivate UCalendar *__RSCalendarCreateUCalendar(RSStringRef calendarID, RSTimeZoneRef tz)
{
    const char *cstr = RSStringGetCStringPtr(calendarID, RSStringEncodingASCII);
    if (nil == cstr)
    {
        //if (RSStringGetCString(localeID, buffer, BUFFER_SIZE, RSStringEncodingASCII)) cstr = buffer;
        
    }
    if (nil == cstr)
    {
        return nil;
    }
    
    UChar ubuffer[BUFFER_SIZE];
    RSStringRef tznam = RSTimeZoneGetName(tz);
    RSIndex cnt = RSStringGetLength(tznam);
    if (BUFFER_SIZE < cnt) cnt = BUFFER_SIZE;

    RSStringGetCharacters(tznam, RSMakeRange(0, cnt), (UniChar *)ubuffer);
    
    UErrorCode status = U_ZERO_ERROR;
    UCalendar *cal = ucal_open(ubuffer, (RSBit32)cnt, cstr, UCAL_DEFAULT, &status);

    return cal;
}
示例#3
0
/**
 * call-seq:
 *     UCalendar.new(zone_id = nil, locale = nil, traditional = false)
 *
 * Creates new instance of UCalendar, for given time zone id (UString),
 * locale (Ruby String), and kind , by default gregorian.
 * New instance has current time.
 *
 */
VALUE icu4r_cal_init (int argc, VALUE * argv, VALUE self)
{
         VALUE zone, loc, cal_type;
	 UChar * zone_id = NULL;
	 char  * locale  = NULL;
	 UCalendarType  c_type = UCAL_GREGORIAN;
	 int32_t n, zone_len =0 , locale_len =0;
	 UCalendar * calendar;
	 UErrorCode  status = U_ZERO_ERROR;
	 n = rb_scan_args(argc, argv, "03", &zone, &loc, &cal_type);
	 if( n >= 1) {
	     Check_Class(zone, rb_cUString);
	     zone_id = ICU_PTR(zone);
	     zone_len = ICU_LEN(zone);
	 }
	 if( n >= 2) {
	     Check_Type(loc, T_STRING);
	     locale = RSTRING_PTR(loc);
	     locale_len = RSTRING_LEN(loc);
	 }
	 if( n >= 3) {
	     if( Qtrue == cal_type ) {
	     	c_type = UCAL_TRADITIONAL;
	     }
	 }
	 calendar = ucal_open(zone_id, zone_len, locale,  c_type, &status);
	 ICU_RAISE(status);
	 DATA_PTR(self) = calendar;
	 return self;
}
示例#4
0
void TestTwoDigitYearDSTParse()
{
    UDateFormat *fullFmt, *fmt;
    UErrorCode status = U_ZERO_ERROR;
    UChar *pattern;
    UDate d;
    UChar *s;
    int32_t pos;

    ctest_setTimeZone(NULL, &status);

    pattern=(UChar*)malloc(sizeof(UChar) * (strlen("EEE MMM dd HH:mm:ss.SSS zzz yyyy G")+1 ));
    u_uastrcpy(pattern, "EEE MMM dd HH:mm:ss.SSS zzz yyyy G");
    fullFmt= udat_open(UDAT_IGNORE, UDAT_IGNORE,"en_US",NULL,0,pattern, u_strlen(pattern),&status);
    if(U_FAILURE(status))    {
        log_err_status(status, "FAIL: Error in creating a date format using udat_openPattern %s\n", 
            myErrorName(status) );
    }
    else {
        log_verbose("PASS: creating dateformat using udat_openPattern() succesful\n");
    
        u_uastrcpy(pattern, "dd-MMM-yy h:mm:ss 'o''clock' a z");
        fmt= udat_open(UDAT_IGNORE,UDAT_IGNORE,"en_US", NULL, 0,pattern, u_strlen(pattern), &status);
        
        
        s=(UChar*)malloc(sizeof(UChar) * (strlen("03-Apr-04 2:20:47 o'clock AM PST")+1) );
        u_uastrcpy(s, "03-Apr-04 2:20:47 o'clock AM PST");
        pos=0;
        d = udat_parse(fmt, s, u_strlen(s), &pos, &status);
        if (U_FAILURE(status)) {
            log_err("FAIL: Could not parse \"%s\"\n", austrdup(s));
        } else {
            UCalendar *cal = ucal_open(NULL, 0, uloc_getDefault(), UCAL_TRADITIONAL, &status);
            if (U_FAILURE(status)) {
                log_err_status(status, "FAIL: Could not open calendar: %s\n", u_errorName(status));
            } else {
                int32_t h;
                ucal_setMillis(cal, d, &status);
                h = ucal_get(cal, UCAL_HOUR_OF_DAY, &status);
                if (U_FAILURE(status)) {
                    log_err("FAIL: Some calendar operations failed");
                } else if (h != 2) {
                    log_err("FAIL: Parse of \"%s\" returned HOUR_OF_DAY %d\n",
                            austrdup(s), h);
                }
                ucal_close(cal);
            }
        }
        
        udat_close(fullFmt);
        udat_close(fmt);
        free(s);
    }
    free(pattern);

    ctest_resetTimeZone();
}
示例#5
0
文件: i18n_date.cpp 项目: djui/i18n
ERL_NIF_TERM open_calendar(ErlNifEnv* env, int argc, 
    const ERL_NIF_TERM argv[])
{
    ERL_NIF_TERM out;
    ErlNifBinary tz;

    cloner* res;
    UCalendar* cal;
    UCalendarType type = UCAL_DEFAULT;
    UErrorCode status = U_ZERO_ERROR;
    char type_atom[ATOM_LEN], locale[LOCALE_LEN];
    
    tz.size = 0; 
    tz.data = 0;

    switch (argc) {
        case 3:
            if (!enif_get_atom(env, argv[2], (char*) type_atom, ATOM_LEN,
                ERL_NIF_LATIN1))
                return enif_make_badarg(env);
            type = parserCalendarType((const char *) type_atom);
        case 2:
            if (!enif_inspect_binary(env, argv[1], &tz))
                return enif_make_badarg(env);
        case 1:
            if (!enif_get_atom(env, argv[0], (char*) locale, 
                    LOCALE_LEN, ERL_NIF_LATIN1))
                return enif_make_badarg(env);
        break;
        default:
            return enif_make_badarg(env);
    }


    /* get a calendar type */
    cal = ucal_open(
        (const UChar *) tz.data,
        (int32_t) tz.size,
        (const char *) locale,
        type,
        &status);
    CHECK(env, status);


    res = (cloner*) enif_alloc_resource(calendar_type, sizeof(cloner));
    if (calendar_open(cal, res)) {
        enif_release_resource(res);
        return enif_make_badarg(env);
    }
    out = enif_make_resource(env, res);
    enif_release_resource(res);
    /* resource now only owned by "Erlang" */
    return out;
}
示例#6
0
void TestQuotePattern161()
{
    UDateFormat *format;
    UCalendar *cal;
    UDate currentTime_1;
    UChar *pattern, *tzID, *exp;
    UChar *dateString;
    UErrorCode status = U_ZERO_ERROR;
    const char* expStr = "04/13/1999 at 10:42:28 AM ";

    ctest_setTimeZone(NULL, &status);

    pattern=(UChar*)malloc(sizeof(UChar) * (strlen("MM/dd/yyyy 'at' hh:mm:ss a zzz")+1) );
    u_uastrcpy(pattern, "MM/dd/yyyy 'at' hh:mm:ss a zzz");
    
    /* 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" */
    /* format= udat_openPattern(pattern, u_strlen(pattern), NULL, &status); */
    format= udat_open(UDAT_IGNORE, UDAT_IGNORE,"en_US", NULL, 0,pattern, u_strlen(pattern), &status);
    if(U_FAILURE(status)){
        log_err_status(status, "error in udat_open: %s\n", myErrorName(status));
        return;
    }
    tzID=(UChar*)malloc(sizeof(UChar) * 4);
    u_uastrcpy(tzID, "PST");
    /* 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" */
    /* cal=ucal_open(tzID, u_strlen(tzID), NULL, UCAL_TRADITIONAL, &status); */
    cal=ucal_open(tzID, u_strlen(tzID), "en_US", UCAL_TRADITIONAL, &status);
    if(U_FAILURE(status)){ log_err("error in ucal_open cal : %s\n", myErrorName(status));    }
    
    ucal_setDateTime(cal, 1999, UCAL_APRIL, 13, 10, 42, 28, &status);
    currentTime_1 = ucal_getMillis(cal, &status);
    
    dateString = myDateFormat(format, currentTime_1);
    exp=(UChar*)malloc(sizeof(UChar) * (strlen(expStr) + 1) );
    u_uastrcpy(exp, expStr);
    
    log_verbose("%s\n", austrdup(dateString) );
    if(u_strncmp(dateString, exp, (int32_t)strlen(expStr)) !=0)
        log_err("Error in formatting a pattern with single quotes\n");

    udat_close(format);
    ucal_close(cal);
    free(exp);
    free(tzID);
    free(pattern);
    
    ctest_resetTimeZone();
}
示例#7
0
/*
Function:
GetLatestJapaneseEra

Gets the latest era in the Japanese calendar.
*/
int32_t GlobalizationNative_GetLatestJapaneseEra()
{
    UErrorCode err = U_ZERO_ERROR;
    UCalendar* pCal = ucal_open(NULL, 0, JAPANESE_LOCALE_AND_CALENDAR, UCAL_TRADITIONAL, &err);

    if (U_FAILURE(err))
        return 0;

    ucal_set(pCal, UCAL_EXTENDED_YEAR, 9999);
    int32_t ret = ucal_get(pCal, UCAL_ERA, &err);

    ucal_close(pCal);
    return U_SUCCESS(err) ? ret : 0;
}
示例#8
0
static void
cal(int32_t month,
    int32_t year,
    UBool useLongNames,
    UErrorCode *status)
{
    UCalendar *c;
    UChar *days [DAY_COUNT];
    UChar *months [MONTH_COUNT];
    int32_t fdow;

    if(U_FAILURE(*status)) return;

    /* Create a new calendar */
    c = ucal_open(0, -1, uloc_getDefault(), UCAL_TRADITIONAL, status);

    /* Determine if we are printing a calendar for one month or for a year */

    /* Print an entire year */
    if(month == -1 && year != -1) {

        /* Set the year */
        ucal_set(c, UCAL_YEAR, year);

        /* Determine the first day of the week */
        fdow = ucal_getAttribute(c, UCAL_FIRST_DAY_OF_WEEK);

        /* Print the calendar for the year */
        print_year(c, days, months, useLongNames, fdow, status);
    }

    /* Print only one month */
    else {

        /* Set the month and the year, if specified */
        if(month != -1)
            ucal_set(c, UCAL_MONTH, month);
        if(year != -1)
            ucal_set(c, UCAL_YEAR, year);

        /* Determine the first day of the week */
        fdow = ucal_getAttribute(c, UCAL_FIRST_DAY_OF_WEEK);

        /* Print the calendar for the month */
        print_month(c, days, useLongNames, fdow, status);
    }

    /* Clean up */
    ucal_close(c);
}
void QIcuTimeZonePrivate::init(const QByteArray &ianaId)
{
    m_id = ianaId;

    const QString id = QString::fromUtf8(m_id);
    UErrorCode status = U_ZERO_ERROR;
    //TODO Use UCAL_GREGORIAN for now to match QLocale, change to UCAL_DEFAULT once full ICU support
    m_ucal = ucal_open(reinterpret_cast<const UChar *>(id.data()), id.size(),
                       QLocale().name().toUtf8(), UCAL_GREGORIAN, &status);

    if (!U_SUCCESS(status)) {
        m_id.clear();
        m_ucal = 0;
    }
}
示例#10
0
U_CAPI int32_t U_EXPORT2 getCurrentYear() {
#if !UCONFIG_NO_FORMATTING
    UErrorCode status=U_ZERO_ERROR;    
    UCalendar *cal = NULL;

    if(currentYear == -1) {
        cal = ucal_open(NULL, -1, NULL, UCAL_TRADITIONAL, &status);
        ucal_setMillis(cal, ucal_getNow(), &status);
        currentYear = ucal_get(cal, UCAL_YEAR, &status);
        ucal_close(cal);
    }
#else
    /* No formatting- no way to set the current year. */
#endif
    return currentYear;
}
/*
 * ICU's Universal Time Scale is designed to be tick-for-tick compatible with
 * .Net System.DateTime. Verify that this is so for the
 * .Net-supported date range (years 1-9999 AD).
 * This requires a proleptic Gregorian calendar because that's what .Net uses.
 * Proleptic: No Julian/Gregorian switchover, or a switchover before
 * any date that we test, that is, before 0001 AD.
 */
static void
TestDotNet() {
    static const UChar utc[] = { 0x45, 0x74, 0x63, 0x2f, 0x47, 0x4d, 0x54, 0 }; /* "Etc/GMT" */
    const int32_t dayMillis = 86400 * INT64_C(1000);    /* 1 day = 86400 seconds */
    const int64_t dayTicks = 86400 * INT64_C(10000000);
    const DotNetDateTimeTicks *dt;
    UCalendar *cal;
    UErrorCode errorCode;
    UDate icuDate;
    int64_t ticks, millis;
    int32_t i;

    /* Open a proleptic Gregorian calendar. */
    errorCode = U_ZERO_ERROR;
    cal = ucal_open(utc, -1, "", UCAL_GREGORIAN, &errorCode);
    ucal_setGregorianChange(cal, -1000000 * (dayMillis * (UDate)1), &errorCode);
    if(U_FAILURE(errorCode)) {
        log_err("ucal_open(UTC/proleptic Gregorian) failed: %s\n", u_errorName(errorCode));
        ucal_close(cal);
        return;
    }
    for(i = 0; i < LENGTHOF(dotNetDateTimeTicks); ++i) {
        /* Test conversion from .Net/Universal time to ICU time. */
        dt = dotNetDateTimeTicks + i;
        millis = utmscale_toInt64(dt->ticks, UDTS_ICU4C_TIME, &errorCode);
        ucal_clear(cal);
        ucal_setDate(cal, dt->year, dt->month - 1, dt->day, &errorCode); /* Java & ICU use January = month 0. */
        icuDate = ucal_getMillis(cal, &errorCode);
        if(millis != icuDate) {
            /* Print days not millis to stay within printf() range. */
            log_err("utmscale_toInt64(ticks[%d], ICU4C)=%dd != %dd=ucal_getMillis(%04d-%02d-%02d)\n",
                    (int)i, (int)(millis/dayMillis), (int)(icuDate/dayMillis), (int)dt->year, (int)dt->month, (int)dt->day);
        }

        /* Test conversion from ICU time to .Net/Universal time. */
        ticks = utmscale_fromInt64((int64_t)icuDate, UDTS_ICU4C_TIME, &errorCode);
        if(ticks != dt->ticks) {
            /* Print days not ticks to stay within printf() range. */
            log_err("utmscale_fromInt64(date[%d], ICU4C)=%dd != %dd=.Net System.DateTime(%04d-%02d-%02d).Ticks\n",
                    (int)i, (int)(ticks/dayTicks), (int)(dt->ticks/dayTicks), (int)dt->year, (int)dt->month, (int)dt->day);
        }
    }

    ucal_close(cal);
}
示例#12
0
/**
 * @bug 4060212
 */
void Test4060212()
{
    int32_t pos;
    UCalendar *cal;
    UDateFormat *formatter, *fmt;
    UErrorCode status = U_ZERO_ERROR;
    UDate myDate;
    UChar *myString;
    UChar dateString[30], pattern[20], tzID[4];
    u_uastrcpy(dateString, "1995-040.05:01:29 -8");
    u_uastrcpy(pattern, "yyyy-DDD.hh:mm:ss z");

    log_verbose( "dateString= %s Using yyyy-DDD.hh:mm:ss\n", austrdup(dateString) );
    status = U_ZERO_ERROR;
    u_uastrcpy(tzID, "PST");

    formatter = udat_open(UDAT_IGNORE,UDAT_IGNORE,"en_US",tzID,-1,pattern, u_strlen(pattern), &status);
    pos=0;
    myDate = udat_parse(formatter, dateString, u_strlen(dateString), &pos, &status);


    fmt = udat_open(UDAT_FULL,UDAT_LONG ,NULL, tzID, -1, 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;
    }
    myString = myFormatit(fmt, myDate);
    cal=ucal_open(tzID, u_strlen(tzID), "en_US", UCAL_GREGORIAN, &status);
    if(U_FAILURE(status)) {
        log_err("FAIL: error in ucal_open caldef : %s\n", myErrorName(status));
    }
    ucal_setMillis(cal, myDate, &status);
    if ((ucal_get(cal, UCAL_DAY_OF_YEAR, &status) != 40)) {
        log_err("Fail: Got  %d Expected 40\n", ucal_get(cal, UCAL_DAY_OF_YEAR, &status));
    }

    udat_close(formatter);
    ucal_close(cal);
    udat_close(fmt);

}
示例#13
0
/* 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();
}
示例#14
0
/*
Function:
GetJapaneseEraInfo

Gets the starting Gregorian date of the specified Japanese Era.
*/
int32_t GlobalizationNative_GetJapaneseEraStartDate(int32_t era,
                                                    int32_t* startYear,
                                                    int32_t* startMonth,
                                                    int32_t* startDay)
{
    *startYear = -1;
    *startMonth = -1;
    *startDay = -1;

    UErrorCode err = U_ZERO_ERROR;
    UCalendar* pCal = ucal_open(NULL, 0, JAPANESE_LOCALE_AND_CALENDAR, UCAL_TRADITIONAL, &err);

    if (U_FAILURE(err))
        return FALSE;

    ucal_set(pCal, UCAL_ERA, era);
    ucal_set(pCal, UCAL_YEAR, 1);

    // UCAL_EXTENDED_YEAR is the gregorian year for the JapaneseCalendar
    *startYear = ucal_get(pCal, UCAL_EXTENDED_YEAR, &err);
    if (U_FAILURE(err))
    {
        ucal_close(pCal);
        return FALSE;
    }

    // set the date to Jan 1
    ucal_set(pCal, UCAL_MONTH, 0);
    ucal_set(pCal, UCAL_DATE, 1);

    int32_t currentEra;
    for (int i = 0; U_SUCCESS(err) && i <= 12; i++)
    {
        currentEra = ucal_get(pCal, UCAL_ERA, &err);
        if (currentEra == era)
        {
            for (int i = 0; U_SUCCESS(err) && i < 31; i++)
            {
                // subtract 1 day at a time until we get out of the specified Era
                ucal_add(pCal, UCAL_DATE, -1, &err);
                currentEra = ucal_get(pCal, UCAL_ERA, &err);
                if (U_SUCCESS(err) && currentEra != era)
                {
                    // add back 1 day to get back into the specified Era
                    ucal_add(pCal, UCAL_DATE, 1, &err);
                    *startMonth =
                        ucal_get(pCal, UCAL_MONTH, &err) + 1; // ICU Calendar months are 0-based, but .NET is 1-based
                    *startDay = ucal_get(pCal, UCAL_DATE, &err);
                    ucal_close(pCal);

                    return UErrorCodeToBool(err);
                }
            }
        }

        // add 1 month at a time until we get into the specified Era
        ucal_add(pCal, UCAL_MONTH, 1, &err);
    }

    ucal_close(pCal);
    return FALSE;
}
示例#15
0
/* 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);
}
示例#16
0
/*
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);
}
示例#17
0
/* {{{ */
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();
	}
}
示例#18
0
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);
}
示例#19
0
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);
     }
}
示例#20
0
// Use LocalXyzPointer types that are not covered elsewhere in the intltest suite.
void LocalPointerTest::TestLocalXyzPointer() {
    IcuTestErrorCode errorCode(*this, "TestLocalXyzPointer");

    static const char *const encoding="ISO-8859-1";
    LocalUConverterSelectorPointer sel(
        ucnvsel_open(&encoding, 1, NULL, UCNV_ROUNDTRIP_SET, errorCode));
    if(errorCode.logIfFailureAndReset("ucnvsel_open()")) {
        return;
    }
    if(sel.isNull()) {
        errln("LocalUConverterSelectorPointer failure");
        return;
    }

#if !UCONFIG_NO_FORMATTING
    LocalUCalendarPointer cal(ucal_open(NULL, 0, "root", UCAL_GREGORIAN, errorCode));
    if(errorCode.logDataIfFailureAndReset("ucal_open()")) {
        return;
    }
    if(cal.isNull()) {
        errln("LocalUCalendarPointer failure");
        return;
    }

    LocalUDateTimePatternGeneratorPointer patgen(udatpg_open("root", errorCode));
    if(errorCode.logDataIfFailureAndReset("udatpg_open()")) {
        return;
    }
    if(patgen.isNull()) {
        errln("LocalUDateTimePatternGeneratorPointer failure");
        return;
    }

    LocalULocaleDisplayNamesPointer ldn(uldn_open("de-CH", ULDN_STANDARD_NAMES, errorCode));
    if(errorCode.logIfFailureAndReset("uldn_open()")) {
        return;
    }
    if(ldn.isNull()) {
        errln("LocalULocaleDisplayNamesPointer failure");
        return;
    }

    UnicodeString hello=UNICODE_STRING_SIMPLE("Hello {0}!");
    LocalUMessageFormatPointer msg(
        umsg_open(hello.getBuffer(), hello.length(), "root", NULL, errorCode));
    if(errorCode.logIfFailureAndReset("umsg_open()")) {
        return;
    }
    if(msg.isNull()) {
        errln("LocalUMessageFormatPointer failure");
        return;
    }
#endif  /* UCONFIG_NO_FORMATTING  */

#if !UCONFIG_NO_NORMALIZATION
    const UNormalizer2 *nfc=unorm2_getNFCInstance(errorCode);
    UnicodeSet emptySet;
    LocalUNormalizer2Pointer fn2(unorm2_openFiltered(nfc, emptySet.toUSet(), errorCode));
    if(errorCode.logIfFailureAndReset("unorm2_openFiltered()")) {
        return;
    }
    if(fn2.isNull()) {
        errln("LocalUNormalizer2Pointer failure");
        return;
    }
#endif /* !UCONFIG_NO_NORMALIZATION */

#if !UCONFIG_NO_IDNA
    LocalUIDNAPointer idna(uidna_openUTS46(0, errorCode));
    if(errorCode.logIfFailureAndReset("uidna_openUTS46()")) {
        return;
    }
    if(idna.isNull()) {
        errln("LocalUIDNAPointer failure");
        return;
    }
#endif  /* !UCONFIG_NO_IDNA */

#if !UCONFIG_NO_REGULAR_EXPRESSIONS
    UnicodeString pattern=UNICODE_STRING_SIMPLE("abc|xy+z");
    LocalURegularExpressionPointer regex(
        uregex_open(pattern.getBuffer(), pattern.length(), 0, NULL, errorCode));
    if(errorCode.logIfFailureAndReset("uregex_open()")) {
        return;
    }
    if(regex.isNull()) {
        errln("LocalURegularExpressionPointer failure");
        return;
    }
#endif /* UCONFIG_NO_REGULAR_EXPRESSIONS */

#if !UCONFIG_NO_TRANSLITERATION
    UnicodeString id=UNICODE_STRING_SIMPLE("Grek-Latn");
    LocalUTransliteratorPointer trans(
        utrans_openU(id.getBuffer(), id.length(), UTRANS_FORWARD, NULL, 0, NULL, errorCode));
    if(errorCode.logIfFailureAndReset("utrans_open()")) {
        return;
    }
    if(trans.isNull()) {
        errln("LocalUTransliteratorPointer failure");
        return;
    }
#endif /* !UCONFIG_NO_TRANSLITERATION */

    // destructors
}
示例#21
0
// Try LocalXyzPointer types with NULL pointers.
void LocalPointerTest::TestLocalXyzPointerNull() {
    {
        IcuTestErrorCode errorCode(*this, "TestLocalXyzPointerNull/LocalUConverterSelectorPointer");
        static const char *const encoding="ISO-8859-1";
        LocalUConverterSelectorPointer null;
        LocalUConverterSelectorPointer sel(
            ucnvsel_open(&encoding, 1, NULL, UCNV_ROUNDTRIP_SET, errorCode));
        sel.adoptInstead(NULL);
    }
#if !UCONFIG_NO_FORMATTING
    {
        IcuTestErrorCode errorCode(*this, "TestLocalXyzPointerNull/LocalUCalendarPointer");
        LocalUCalendarPointer null;
        LocalUCalendarPointer cal(ucal_open(NULL, 0, "root", UCAL_GREGORIAN, errorCode));
        if(!errorCode.logDataIfFailureAndReset("ucal_open()")) {
            cal.adoptInstead(NULL);
        }
    }
    {
        IcuTestErrorCode errorCode(*this, "TestLocalXyzPointerNull/LocalUDateTimePatternGeneratorPointer");
        LocalUDateTimePatternGeneratorPointer null;
        LocalUDateTimePatternGeneratorPointer patgen(udatpg_open("root", errorCode));
        patgen.adoptInstead(NULL);
    }
    {
        IcuTestErrorCode errorCode(*this, "TestLocalXyzPointerNull/LocalUMessageFormatPointer");
        UnicodeString hello=UNICODE_STRING_SIMPLE("Hello {0}!");
        LocalUMessageFormatPointer null;
        LocalUMessageFormatPointer msg(
            umsg_open(hello.getBuffer(), hello.length(), "root", NULL, errorCode));
        msg.adoptInstead(NULL);
    }
#endif /* !UCONFIG_NO_FORMATTING */

#if !UCONFIG_NO_REGULAR_EXPRESSIONS
    {
        IcuTestErrorCode errorCode(*this, "TestLocalXyzPointerNull/LocalURegularExpressionPointer");
        UnicodeString pattern=UNICODE_STRING_SIMPLE("abc|xy+z");
        LocalURegularExpressionPointer null;
        LocalURegularExpressionPointer regex(
            uregex_open(pattern.getBuffer(), pattern.length(), 0, NULL, errorCode));
        if(!errorCode.logDataIfFailureAndReset("urege_open()")) {
            regex.adoptInstead(NULL);
        }
    }
#endif /* !UCONFIG_NO_REGULAR_EXPRESSIONS */

#if !UCONFIG_NO_TRANSLITERATION
    {
        IcuTestErrorCode errorCode(*this, "TestLocalXyzPointerNull/LocalUTransliteratorPointer");
        UnicodeString id=UNICODE_STRING_SIMPLE("Grek-Latn");
        LocalUTransliteratorPointer null;
        LocalUTransliteratorPointer trans(
            utrans_openU(id.getBuffer(), id.length(), UTRANS_FORWARD, NULL, 0, NULL, errorCode));
        if(!errorCode.logDataIfFailureAndReset("utrans_openU()")) {
            trans.adoptInstead(NULL);
        }
    }
#endif /* !UCONFIG_NO_TRANSLITERATION */

}
示例#22
0
/**
 * @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);
}
示例#23
0
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();
}
/*
PAL Function:
GetLocaleInfoInt

Obtains integer locale information
Returns 1 for success, 0 otherwise
*/
extern "C" int32_t GlobalizationNative_GetLocaleInfoInt(
    const UChar* localeName, LocaleNumberData localeNumberData, int32_t* value)
{
    UErrorCode status = U_ZERO_ERROR;
    char locale[ULOC_FULLNAME_CAPACITY];
    GetLocale(localeName, locale, ULOC_FULLNAME_CAPACITY, false, &status);

    if (U_FAILURE(status))
    {
        return UErrorCodeToBool(U_ILLEGAL_ARGUMENT_ERROR);
    }

    switch (localeNumberData)
    {
    case LanguageId:
        *value = uloc_getLCID(locale);
        break;
    case MeasurementSystem:
        status = GetMeasurementSystem(locale, value);
        break;
    case FractionalDigitsCount:
    {
        UNumberFormat* numformat = unum_open(UNUM_DECIMAL, NULL, 0, locale, NULL, &status);
        if (U_SUCCESS(status))
        {
            *value = unum_getAttribute(numformat, UNUM_MAX_FRACTION_DIGITS);
            unum_close(numformat);
        }
        break;
    }
    case NegativeNumberFormat:
        *value = GetNumberNegativePattern(locale);
        break;
    case MonetaryFractionalDigitsCount:
    {
        UNumberFormat* numformat = unum_open(UNUM_CURRENCY, NULL, 0, locale, NULL, &status);
        if (U_SUCCESS(status))
        {
            *value = unum_getAttribute(numformat, UNUM_MAX_FRACTION_DIGITS);
            unum_close(numformat);
        }
        break;
    }
    case PositiveMonetaryNumberFormat:
        *value = GetCurrencyPositivePattern(locale);
        break;
    case NegativeMonetaryNumberFormat:
        *value = GetCurrencyNegativePattern(locale);
        break;
    case FirstWeekOfYear:
    {
        // corresponds to DateTimeFormat.CalendarWeekRule
        UCalendar* pCal = ucal_open(nullptr, 0, locale, UCAL_TRADITIONAL, &status);
        UCalendarHolder calHolder(pCal, status);

        if (U_SUCCESS(status))
        {
            // values correspond to LOCALE_IFIRSTWEEKOFYEAR
            int minDaysInWeek = ucal_getAttribute(pCal, UCAL_MINIMAL_DAYS_IN_FIRST_WEEK);
            if (minDaysInWeek == 1)
            {
                *value = CalendarWeekRule::FirstDay;
            }
            else if (minDaysInWeek == 7)
            {
                *value = CalendarWeekRule::FirstFullWeek;
            }
            else if (minDaysInWeek >= 4)
            {
                *value = CalendarWeekRule::FirstFourDayWeek;
            }
            else
            {
                status = U_UNSUPPORTED_ERROR;
            }
        }
        break;
    }
    case ReadingLayout:
    {
        // coresponds to values 0 and 1 in LOCALE_IREADINGLAYOUT (values 2 and 3 not
        // used in coreclr)
        //  0 - Left to right (such as en-US)
        //  1 - Right to left (such as arabic locales)
        ULayoutType orientation = uloc_getCharacterOrientation(locale, &status);
        // alternative implementation in ICU 54+ is uloc_isRightToLeft() which
        // also supports script tags in locale
        if (U_SUCCESS(status))
        {
            *value = (orientation == ULOC_LAYOUT_RTL) ? 1 : 0;
        }
        break;
    }
    case FirstDayofWeek:
    {
        UCalendar* pCal = ucal_open(nullptr, 0, locale, UCAL_TRADITIONAL, &status);
        UCalendarHolder calHolder(pCal, status);

        if (U_SUCCESS(status))
        {
            *value = ucal_getAttribute(pCal, UCAL_FIRST_DAY_OF_WEEK) - 1; // .NET is 0-based and ICU is 1-based
        }
        break;
    }
    case NegativePercentFormat:
        *value = GetPercentNegativePattern(locale);
        break;
    case PositivePercentFormat:
        *value = GetPercentPositivePattern(locale);
        break;
    default:
        status = U_UNSUPPORTED_ERROR;
        assert(false);
        break;
    }

    return UErrorCodeToBool(status);
}