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.
/* 1st example: format the dates in millis 100000000 and 2000000000 */UErrorCodestatus=U_ZERO_ERROR;int32_ti,myStrlen=0;UChar*myString;UDatemyDateArr[]={0.0,100000000.0,2000000000.0};// test valuesUDateFormat*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);}}
Parse
To parse a date for a different locale, specify it in the locale call. This call creates a formatting object.
/* 2nd example: parse a date with short French date/time formatter */UDateFormat*df=udat_open(UDAT_SHORT,UDAT_SHORT,"fr_FR","GMT",&status);UErrorCodestatus=U_ZERO_ERROR;int32_tparsepos=0;UDatemyDate=udat_parse(df,myString,u_strlen(myString),&parsepos,&status);
Java
importjava.text.FieldPosition;importjava.text.ParseException;importjava.util.Calendar;importjava.util.Date;importjava.util.Locale;importcom.ibm.icu.text.DateFormat;publicclassTestDateTimeFormat{publicvoidrun(){// Formatting DatesDateFormatdfUS=DateFormat.getDateInstance(DateFormat.FULL,Locale.US);DateFormatdfFrance=DateFormat.getDateInstance(DateFormat.FULL,Locale.FRANCE);StringBuffersb=newStringBuffer();Calendarc=Calendar.getInstance();Dated=c.getTime();sb=dfUS.format(d,sb,newFieldPosition(0));System.out.println(sb.toString());StringBuffersbf=newStringBuffer();sbf=dfFrance.format(d,sbf,newFieldPosition(0));System.out.println(sbf.toString());StringBuffersbg=newStringBuffer();DateFormatdfg=DateFormat.getDateTimeInstance(DateFormat.FULL,DateFormat.SHORT);FieldPositionpos=newFieldPosition(DateFormat.MINUTE_FIELD);sbg=dfg.format(d,sbg,pos);System.out.println(sbg.toString());System.out.println(sbg.toString().substring(pos.getBeginIndex(),pos.getEndIndex()));// Parsing DatesStringdateString_US="Thursday, February 7, 2008";StringdateString_FRANCE="jeudi 7 février 2008";try{DateparsedDate_US=dfUS.parse(dateString_US);DateparsedDate_FRANCE=dfFrance.parse(dateString_FRANCE);System.out.println(parsedDate_US.toString());System.out.println(parsedDate_FRANCE.toString());}catch(ParseExceptionpe){System.out.println("Exception while parsing :"+pe);}}publicstaticvoidmain(Stringargs[]){newTestDateTimeFormat().run();}}
Getting Specific Date Fields
To get specific fields of a date, you can use the FieldPosition function for C++ or UFieldPosition function for C.
UErrorCodestatus=U_ZERO_ERROR;UFieldPositionpos;UChar*myString;int32_tmyStrlen=0;charbuffer[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]);
DateTimePatternGenerator
This class lets you get a different variety of patterns, such as month+day. The following illustrates this in Java, C++ and C.
Java
// set up the generatorDateTimePatternGeneratorgenerator=DateTimePatternGenerator.getInstance(locale);// get a pattern for an abbreviated month and dayfinalStringpattern=generator.getBestPattern("MMMd");SimpleDateFormatformatter=newSimpleDateFormat(pattern,locale);// use it to format (or parse)Stringformatted=formatter.format(newDate());// for French, the result is "13 sept."
C++
// set up the generatorstatus=U_ZERO_ERROR;DateTimePatternGenerator*generator=DateTimePatternGenerator::createInstance(locale,status);if(U_FAILURE(status)){return;}// get a pattern for an abbreviated month and dayUnicodeStringpattern=generator->getBestPattern(UnicodeString("MMMd"),status);SimpleDateFormat*formatter=newSimpleDateFormat(pattern,locale,status);// use it to format (or parse)UnicodeStringformatted;formatted=formatter->format(Calendar::getNow(),formatted,status);// for French, the result is "13 sept."
C
constUCharskeleton[]={'M','M','M','d',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,NULL,-1,pattern,length,&status);/* 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." */
Changing the TimeZone Formatting Style
It also contains some helper functions for parsing patterns. Here’s an example of replacing the kind of timezone used in a pattern.
Java
/**
* Replace the zone string with a different type, eg v's for z's, etc.
* <p>Called with a pattern, such as one gotten from
* <pre>
* String pattern = ((SimpleDateFormat)
* DateFormat.getTimeInstance(style, locale)).toPattern();
* </pre>
* @param pattern original pattern to change, such as "HH:mm zzzz"
* @param newZone Must be: z, zzzz, Z, ZZZZ, v, vvvv, V, or VVVV
* @return
*/publicStringreplaceZoneString(Stringpattern,StringnewZone){DateTimePatternGenerator.FormatParserformatParser=newDateTimePatternGenerator.FormatParser();finalListitemList=formatParser.set(pattern).getItems();booleanfound=false;for(inti=0;i<itemList.size();++i){Objectitem=itemList.get(i);if(iteminstanceofVariableField){// the first character of the variable field determines the type,// according to CLDR.StringvariableField=item.toString();switch(variableField.charAt(0)){case'z':case'Z':case'v':case'V':if(!variableField.equals(newZone)){found=true;itemList.set(i,newVariableField(newZone));}break;}}}returnfound?formatParser.toString():pattern;}