
Format Date and Time Examples
Overview
The ICU DateFormat interface enables you to format a date in milliseconds into a string representation of the date. Also, the interface enables you to parse the string back to the internal date representation in milliseconds.
C++
DateFormat* df = DateFormat::createDateInstance(); UnicodeString myString; UDate myDateArr[] = { 0.0, 100000000.0, 2000000000.0 }; for (int32_t i = 0; i < 3; ++i) { myString.remove(); cout << df->format( myDateArr[i], myString ) << endl; } |
C
/* 1st example: format the dates in millis 100000000 and 2000000000 */ UErrorCode status=U_ZERO_ERROR; int32_t i, myStrlen=0; UChar* myString; UDate myDateArr[] = { 0.0, 100000000.0, 2000000000.0 }; // test values UDateFormat* df = udat_open(UCAL_DEFAULT, UCAL_DEFAULT, NULL, "GMT", &status); for (i = 0; i < 3; ++i) { myStrlen = udat_format(df, myDateArr[i], NULL, myStrlen, NULL, &status); if(status==U_BUFFER_OVERFLOW_ERROR){ status=U_ZERO_ERROR; myString=(UChar*)malloc(sizeof(UChar) * (myStrlen+1) ); udat_format(df, myDateArr[i], myString, myStrlen+1, NULL, &status); printf("%s\n", austrdup(myString) ); /* austrdup( a function used to convert UChar* to char*) */ free(myString); } } |
To parse a date for a different locale, specify it in the locale call. This call creates a formatting object.
C++
DateFormat* df = DateFormat::createDateInstance ( DateFormat::SHORT, Locale::getFrance()); |
C
/* 2nd example: parse a date with short French date/time formatter */ UDateFormat* df = udat_open(UDAT_SHORT, UDAT_SHORT, "fr_FR", "GMT", &status); UErrorCode status = U_ZERO_ERROR; int32_t parsepos=0; UDate myDate = udat_parse(df, myString, u_strlen(myString), &parsepos, &status); |
To get specific fields of a date, you can use the FieldPosition function for C++ or UFieldPosition function for C.
C++
UErrorCode status = U_ZERO_ERROR; FieldPosition pos(DateFormat::YEAR_FIELD) UDate myDate = Calendar::getNow(); UnicodeString str; DateFormat* df = DateFormat::createDateInstance ( DateFormat::LONG, Locale::getFrance()); df->format(myDate, str, pos, status); cout << pos.getBeginIndex() << "," << pos. getEndIndex() << endl; |
C
UErrorCode status = U_ZERO_ERROR; UFieldPosition pos; UChar *myString; int32_t myStrlen = 0; char buffer[1024]; pos.field = 1; /* Same as the DateFormat::EField enum */ UDateFormat* dfmt = udat_open(UCAL_DEFAULT, UCAL_DEFAULT, NULL, "PST", &status); myStrlen = udat_format(dfmt, myDate, NULL, myStrlen, &pos, &status); if (status==U_BUFFER_OVERFLOW_ERROR){ status=U_ZERO_ERROR; myString=(UChar*)malloc(sizeof(UChar) * (myStrlen+1) ); udat_format(dfmt, myDate, myString, myStrlen+1, &pos, &status); } printf("date format: %s\n", u_austrcpy(buffer, myString)); buffer[pos.endIndex] = 0; // NULL terminate the string. printf("UFieldPosition position equals %s\n", &buffer[pos.beginIndex]); |
Copyright (c) 2000 - 2005 IBM and Others - PDF Version - Feedback: http://icu.sourceforge.net/contacts.html
User Guide for ICU v3.4 Generated 2005-07-27.