예제 #1
0
파일: cnmdptst.c 프로젝트: winlibs/icu4c
/*Test Various format patterns*/
static void TestPatterns(void)
{
    int32_t pat_length, i, lneed;
    UNumberFormat *fmt;
    UChar upat[5];
    UChar unewpat[5];
    UChar unum[5];
    UChar *unewp=NULL;
    UChar *str=NULL;
    UErrorCode status = U_ZERO_ERROR;
    const char* pat[]    = { "#.#", "#.", ".#", "#" };
    const char* newpat[] = { "0.#", "0.", "#.0", "0" };
    const char* num[]    = { "0",   "0.", ".0", "0" };

    log_verbose("\nTesting different format patterns\n");
    pat_length = UPRV_LENGTHOF(pat);
    for (i=0; i < pat_length; ++i)
    {
        status = U_ZERO_ERROR;
        u_uastrcpy(upat, pat[i]);
        fmt= unum_open(UNUM_IGNORE,upat, u_strlen(upat), "en_US",NULL, &status);
        if (U_FAILURE(status)) {
            log_err_status(status, "FAIL: Number format constructor failed for pattern %s -> %s\n", pat[i], u_errorName(status));
            continue;
        }
        lneed=0;
        lneed=unum_toPattern(fmt, FALSE, NULL, lneed, &status);
        if(status==U_BUFFER_OVERFLOW_ERROR){
            status= U_ZERO_ERROR;
            unewp=(UChar*)malloc(sizeof(UChar) * (lneed+1) );
            unum_toPattern(fmt, FALSE, unewp, lneed+1, &status);
        }
        if(U_FAILURE(status)){
            log_err("FAIL: Number format extracting the pattern failed for %s\n", pat[i]);
        }
        u_uastrcpy(unewpat, newpat[i]);
        if(u_strcmp(unewp, unewpat) != 0)
            log_err("FAIL: Pattern  %s should be transmute to %s; %s seen instead\n", pat[i], newpat[i],  austrdup(unewp) );

        lneed=0;
        lneed=unum_format(fmt, 0, NULL, lneed, NULL, &status);
        if(status==U_BUFFER_OVERFLOW_ERROR){
            status=U_ZERO_ERROR;
            str=(UChar*)malloc(sizeof(UChar) * (lneed+1) );
            unum_format(fmt, 0, str, lneed+1,  NULL, &status);
        }
        if(U_FAILURE(status)) {
            log_err("Error in formatting using unum_format(.....): %s\n", myErrorName(status) );
        }
        u_uastrcpy(unum, num[i]);
        if (u_strcmp(str, unum) != 0)
        {
            log_err("FAIL: Pattern %s should format zero as %s; %s Seen instead\n", pat[i], num[i], austrdup(str) );

        }
        free(unewp);
        free(str);
        unum_close(fmt);
    }
}
예제 #2
0
파일: sprintf.c 프로젝트: gitpan/ponie
/* HSYS */
int32_t
u_sprintf_integer_handler(u_localized_string *output,
                          const u_sprintf_spec_info     *info,
                          const ufmt_args            *args)
{
    long            num         = (long) (args[0].intValue);
    UNumberFormat        *format;
    UChar            result        [USPRINTF_BUFFER_SIZE];
    int32_t        minDigits     = -1;
    UErrorCode        status        = U_ZERO_ERROR;


    /* mask off any necessary bits */
    if(info->fIsShort)
        num &= UINT16_MAX;
    else if(! info->fIsLong || ! info->fIsLongLong)
        num &= UINT32_MAX;

    /* get the formatter */
    format = u_locbund_getNumberFormat(output->fBundle);

    /* handle error */
    if(format == 0)
        return 0;

    /* set the appropriate flags on the formatter */

    /* set the minimum integer digits */
    if(info->fPrecision != -1) {
        /* clone the stream's bundle if it isn't owned */
        if(! output->fOwnBundle) {
            output->fBundle     = u_locbund_clone(output->fBundle);
            output->fOwnBundle = TRUE;
            format           = u_locbund_getNumberFormat(output->fBundle);
        }

        /* set the minimum # of digits */
        minDigits = unum_getAttribute(format, UNUM_MIN_INTEGER_DIGITS);
        unum_setAttribute(format, UNUM_MIN_INTEGER_DIGITS, info->fPrecision);
    }

    /* set whether to show the sign */
    if(info->fShowSign) {
        /* clone the stream's bundle if it isn't owned */
        if(! output->fOwnBundle) {
            output->fBundle     = u_locbund_clone(output->fBundle);
            output->fOwnBundle = TRUE;
            format           = u_locbund_getNumberFormat(output->fBundle);
        }

        u_sprintf_set_sign(format, info, &status);
    }

    /* format the number */
    unum_format(format, num, result, USPRINTF_BUFFER_SIZE, 0, &status);

    /* restore the number format */
    if(minDigits != -1) {
        unum_setAttribute(format, UNUM_MIN_INTEGER_DIGITS, minDigits);
    }

    return u_sprintf_pad_and_justify(output, info, result, u_strlen(result));
}
예제 #3
0
파일: cnmdptst.c 프로젝트: winlibs/icu4c
/**
 * Test the functioning of the secondary grouping value.
 */
static void TestSecondaryGrouping(void) {
    UErrorCode status = U_ZERO_ERROR;
    UNumberFormat *f = NULL, *g= NULL;
    UNumberFormat *us = unum_open(UNUM_DECIMAL,NULL,0, "en_US", NULL,&status);
    UFieldPosition pos;
    UChar resultBuffer[512];
    int32_t l = 1876543210L;
    UBool ok = TRUE;
    UChar buffer[512];
    int32_t i;
    UBool expectGroup = FALSE, isGroup = FALSE;

    u_uastrcpy(buffer, "#,##,###");
    f = unum_open(UNUM_IGNORE,buffer, -1, "en_US",NULL, &status);
    if (U_FAILURE(status)) {
        log_data_err("Error DecimalFormat ct -> %s (Are you missing data?)\n", u_errorName(status));
        return;
    }

    pos.field = 0;
    unum_format(f, (int32_t)123456789L, resultBuffer, 512 , &pos, &status);
    u_uastrcpy(buffer, "12,34,56,789");
    if ((u_strcmp(resultBuffer, buffer) != 0) || U_FAILURE(status))
    {
        log_err("Fail: Formatting \"#,##,###\" pattern with 123456789 got %s, expected %s\n", austrdup(resultBuffer), "12,34,56,789");
    }
    if (pos.beginIndex != 0 && pos.endIndex != 12) {
        log_err("Fail: Formatting \"#,##,###\" pattern pos = (%d, %d) expected pos = (0, 12)\n", pos.beginIndex, pos.endIndex);
    }
    memset(resultBuffer,0, sizeof(UChar)*512);
    unum_toPattern(f, FALSE, resultBuffer, 512, &status);
    u_uastrcpy(buffer, "#,##,##0");
    if ((u_strcmp(resultBuffer, buffer) != 0) || U_FAILURE(status))
    {
        log_err("Fail: toPattern() got %s, expected %s\n", austrdup(resultBuffer), "#,##,##0");
    }
    memset(resultBuffer,0, sizeof(UChar)*512);
    u_uastrcpy(buffer, "#,###");
    unum_applyPattern(f, FALSE, buffer, -1,NULL,NULL);
    if (U_FAILURE(status))
    {
        log_err("Fail: applyPattern call failed\n");
    }
    unum_setAttribute(f, UNUM_SECONDARY_GROUPING_SIZE, 4);
    unum_format(f, (int32_t)123456789L, resultBuffer, 512 , &pos, &status);
    u_uastrcpy(buffer, "12,3456,789");
    if ((u_strcmp(resultBuffer, buffer) != 0) || U_FAILURE(status))
    {
        log_err("Fail: Formatting \"#,###\" pattern with 123456789 got %s, expected %s\n", austrdup(resultBuffer), "12,3456,789");
    }
    memset(resultBuffer,0, sizeof(UChar)*512);
    unum_toPattern(f, FALSE, resultBuffer, 512, &status);
    u_uastrcpy(buffer, "#,####,##0");
    if ((u_strcmp(resultBuffer, buffer) != 0) || U_FAILURE(status))
    {
        log_err("Fail: toPattern() got %s, expected %s\n", austrdup(resultBuffer), "#,####,##0");
    }
    memset(resultBuffer,0, sizeof(UChar)*512);
    g = unum_open(UNUM_DECIMAL, NULL,0,"hi_IN",NULL, &status);
    if (U_FAILURE(status))
    {
        log_err("Fail: Cannot create UNumberFormat for \"hi_IN\" locale.\n");
    }

    unum_format(g, l, resultBuffer, 512, &pos, &status);
    unum_close(g);
    /* expect "1,87,65,43,210", but with Hindi digits */
    /*         01234567890123                         */
    if (u_strlen(resultBuffer) != 14) {
        ok = FALSE;
    } else {
        for (i=0; i<u_strlen(resultBuffer); ++i) {
            expectGroup = FALSE;
            switch (i) {
            case 1:
            case 4:
            case 7:
            case 10:
                expectGroup = TRUE;
                break;
            }
            /* Later -- fix this to get the actual grouping */
            /* character from the resource bundle.          */
            isGroup = (UBool)(resultBuffer[i] == 0x002C);
            if (isGroup != expectGroup) {
                ok = FALSE;
                break;
            }
        }
    }
    if (!ok) {
        log_err("FAIL  Expected %s x hi_IN -> \"1,87,65,43,210\" (with Hindi digits), got %s\n", "1876543210L", resultBuffer);
    }
    unum_close(f);
    unum_close(us);
}
예제 #4
0
파일: cnmdptst.c 프로젝트: winlibs/icu4c
/* Test the handling of quotes*/
static void TestQuotes(void)
{
    int32_t lneed;
    UErrorCode status=U_ZERO_ERROR;
    UChar pat[15];
    UChar res[15];
    UChar *str=NULL;
    UNumberFormat *fmt;
    char tempBuf[256];
    log_verbose("\nTestting the handling of quotes in number format\n");
    u_uastrcpy(pat, "a'fo''o'b#");
    fmt =unum_open(UNUM_IGNORE,pat, u_strlen(pat), "en_US",NULL, &status);
    if(U_FAILURE(status)){
        log_err_status(status, "Error in number format costruction using pattern \"a'fo''o'b#\" -> %s\n", u_errorName(status));
    }
    lneed=0;
    lneed=unum_format(fmt, 123, NULL, lneed, NULL, &status);
    if(status==U_BUFFER_OVERFLOW_ERROR){
        status=U_ZERO_ERROR;
        str=(UChar*)malloc(sizeof(UChar) * (lneed+1) );
        unum_format(fmt, 123, str, lneed+1,  NULL, &status);
    }
    if(U_FAILURE(status) || !str) {
        log_err_status(status, "Error in formatting using unum_format(.....): %s\n", myErrorName(status) );
        return;
    }
    log_verbose("Pattern \"%s\" \n", u_austrcpy(tempBuf, pat) );
    log_verbose("Format 123 -> %s\n", u_austrcpy(tempBuf, str) );
    u_uastrcpy(res, "afo'ob123");
    if(u_strcmp(str, res) != 0)
        log_err("FAIL: Expected afo'ob123");

    free(str);
    unum_close(fmt);


    u_uastrcpy(pat, "");
    u_uastrcpy(pat, "a''b#");


    fmt =unum_open(UNUM_IGNORE,pat, u_strlen(pat), "en_US",NULL, &status);
    if(U_FAILURE(status)){
        log_err("Error in number format costruction using pattern \"a''b#\"\n");
    }
    lneed=0;
    lneed=unum_format(fmt, 123, NULL, lneed, NULL, &status);
    if(status==U_BUFFER_OVERFLOW_ERROR){
        status=U_ZERO_ERROR;
        str=(UChar*)malloc(sizeof(UChar) * (lneed+1) );
        unum_format(fmt, 123, str, lneed+1,  NULL, &status);
    }
    if(U_FAILURE(status)) {
        log_err("Error in formatting using unum_format(.....): %s\n", myErrorName(status) );
    }
    log_verbose("Pattern \"%s\" \n", u_austrcpy(tempBuf, pat) );
    log_verbose("Format 123 -> %s\n", u_austrcpy(tempBuf, str) );
    u_uastrcpy(res, "");
    u_uastrcpy(res, "a'b123");
    if(u_strcmp(str, res) != 0)
        log_err("FAIL: Expected a'b123\n");

    free(str);
    unum_close(fmt);
}
예제 #5
0
파일: icu_numeric.c 프로젝트: richo/icu
/**
 *  call-seq:
 *     23874.localize(:decimal, 'es_ES') => 23.874
 */
VALUE rb_numeric_localize(int argc, VALUE *argv, VALUE self)
{
	VALUE style, options;
	UNumberFormatStyle formatStyle;
	char *locale = NULL;

	UNumberFormat *format;
	UErrorCode status;

	UChar result[256];
	/* arguments */
	rb_scan_args(argc, argv, "02", &style, &options);
	if (style == Qnil) {
		formatStyle = UNUM_DECIMAL;
	} else {
		ID style_ID;

		Check_Type(style, T_SYMBOL);
		style_ID = SYM2ID(style);
		if (style_ID == rb_intern("decimal")) {
			formatStyle = UNUM_DECIMAL;
		} else if (style_ID == rb_intern("currency")) {
			formatStyle = UNUM_CURRENCY;
		} else if (style_ID == rb_intern("percent")) {
			formatStyle = UNUM_PERCENT;
		} else if (style_ID == rb_intern("scientific")) {
			formatStyle = UNUM_SCIENTIFIC;
		} else if (style_ID == rb_intern("spellout")) {
			formatStyle = UNUM_SPELLOUT;
		} else {
			rb_raise(rb_eArgError, "unsupported format style %s", rb_id2name(style_ID));
		}
	}
	if (options != Qnil) {
		VALUE rb_locale;

		Check_Type(options, T_HASH);
		rb_locale = rb_hash_aref(options, ID2SYM(rb_intern("locale")));
		if (rb_locale != Qnil) {
			locale = StringValuePtr(rb_locale);
		}
	}
	/* formatter */
	status = U_ZERO_ERROR;
    format = unum_open(formatStyle, NULL, 0, locale, NULL, &status);
    RAISE_ON_ERROR(status);
    /* set format attributes */
	if (options != Qnil) {
		VALUE currency, precision, round_mode, round_increment;

		switch (formatStyle) {
			case UNUM_CURRENCY:
				currency = rb_hash_aref(options, ID2SYM(rb_intern("currency")));
				if (currency != Qnil) {
					UChar *uStr;
					int32_t uStrLen;

					uStr = u_strFromRString(currency, &uStrLen);
					status = U_ZERO_ERROR;
					unum_setTextAttribute(format, UNUM_CURRENCY_CODE, uStr, uStrLen, &status);
					RAISE_ON_ERROR(status);
				}
			case UNUM_DECIMAL:
				/* precision */
				precision = rb_hash_aref(options, ID2SYM(rb_intern("precision")));
				if (precision != Qnil) {
					Check_Type(precision, T_FIXNUM);
					status = U_ZERO_ERROR;
					unum_setAttribute(format, UNUM_FRACTION_DIGITS, NUM2INT(precision));
					RAISE_ON_ERROR(status);
				}

				round_mode = rb_hash_aref(options, ID2SYM(rb_intern("round_mode")));
				if (round_mode != Qnil) {
					ID round_mode_ID;
					UNumberFormatRoundingMode rounding_mode;

					Check_Type(round_mode, T_SYMBOL);
					round_mode_ID = SYM2ID(round_mode);
					if (round_mode_ID == rb_intern("ceil")) {
						rounding_mode = UNUM_ROUND_CEILING;
					} else if (round_mode_ID == rb_intern("floor")) {
						rounding_mode = UNUM_ROUND_FLOOR;
					} else if (round_mode_ID == rb_intern("down")) {
						rounding_mode = UNUM_ROUND_DOWN;
					} else if (round_mode_ID == rb_intern("up")) {
						rounding_mode = UNUM_ROUND_UP;
					} else if (round_mode_ID == rb_intern("halfeven")) {
						rounding_mode = UNUM_FOUND_HALFEVEN;
					} else if (round_mode_ID == rb_intern("halfdown")) {
						rounding_mode = UNUM_ROUND_HALFDOWN;
					} else if (round_mode_ID == rb_intern("halfup")) {
						rounding_mode = UNUM_ROUND_HALFUP;
					} else {
						rb_raise(rb_eArgError, "unsupported rounding mode '%s'", rb_id2name(round_mode_ID));
					}
					status = U_ZERO_ERROR;
					unum_setAttribute(format, UNUM_ROUNDING_MODE, rounding_mode);
					RAISE_ON_ERROR(status);
				}
				round_increment = rb_hash_aref(options, ID2SYM(rb_intern("round_increment")));
				if (round_increment != Qnil) {
					Check_Type(round_increment, T_FLOAT);
					status = U_ZERO_ERROR;
					unum_setDoubleAttribute(format, UNUM_ROUNDING_INCREMENT, NUM2DBL(round_increment));
					RAISE_ON_ERROR(status);
				}
		}
	}
	/* format */
	status = U_ZERO_ERROR;
    switch (TYPE(self)) {
    	case T_FIXNUM:
    		unum_format(format, NUM2INT(self), result, 256, NULL, &status);
    		break;
    	case T_FLOAT:
    		unum_formatDouble(format, NUM2DBL(self), result, 256, NULL, &status);
    		break;
    	case T_BIGNUM:
			unum_formatInt64(format, rb_big2ll(self), result, 256, NULL, &status);
    		break;

    }
    RAISE_ON_ERROR(status);
    /* free resources */
    unum_close(format);

    return u_strToRString(result, -1);
}
예제 #6
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);
}
예제 #7
0
/* 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);
}