Languages Around The World

Formatting Dates and Times

Formatting Dates and Times Overview

Date and time formatters are used to convert dates and times from their internal representations to textual form and back again in a language-independent manner. The date and time formatters use UDate, which is the internal representation. Converting from the internal representation (milliseconds since midnight, January 1, 1970) to text is known as "formatting," and converting from text to milliseconds is known as "parsing."

ICU has three formatting classes for creating dates and times that are easily localizable:

  1. DateFormat

  2. SimpleDateFormat

  3. DateFormatSymbols

NoteWARNING - in ICU 3.8, the behavior of date formatting and parsing has changed significantly, perhaps requiring recoding on your part depending on your usage. The goal of making the change was to return more understandable results from formatting timezones, but a byproduct is that the result from formatting with strings z, zzzz, v or vvvv are no longer unique, and thus no longer roundtrips. That is, if you use a date format with one of these strings, producing a certain output, you can no longer parse that output and expect to recover the original timezone.
What you will be able to get is a related, "best fit" mapping for the name, based on the region associated with the current locale and the mappings found in CLDR's supplemental data: for example, if you format the time zone "America/Denver", getting "Heure des Rocheuses" in French, and then parse, the resulting time zone would be "America/Denver". However, if the locale in use has the region "CA" (such as en-CA or fr-CA), the zone "America/Edmonton" would be retrieved.
If you require roundtripping, you will need to change your code to use "VVVV" instead. If you are working with date patterns based on a locale, then the workaround is to use the DateTimePatternGenerator to convert the format you get for a locale to using "VVVV". See date and time formatting examples .

DateFormat

DateFormat helps format and parse dates for any locale. Your code can be completely independent of the locale conventions for months, days of the week, or calendar format.

Formatting Dates

The DateFormat interface in ICU enables you to format a Date in milliseconds into a string representation of the date. It also parses the string back to the internal Date representation in milliseconds.

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;
}

To format a date for a different Locale, specify it in the call to:

DateFormat* df = DateFormat::createDateInstance
   ( DateFormat::SHORT, Locale::getFrance());

Parsing Dates

Use a DateFormat to parse also:

UErrorCode status = ZERO_ERROR;
UDate myDate = df->parse(myString, status);

Producing Normal Date Formats for a Locale

Use createDateInstance to produce the normal date format for that country. There are other static factory methods available. Use createTimeInstance to produce the normal time format for that country. Use createDateTimeInstance to produce a DateFormat that formats both date and time. You can pass different options to these factory methods to control the length of the result; from SHORT to MEDIUM to LONG to FULL. The exact result depends on the locale, but generally:

  1. SHORT is numeric, such as 12/13/52 or 3:30pm

  2. MEDIUM is longer, such as Jan. 12, 1952

  3. LONG is longer, such as January 12, 1952 or 3:30:32pm

  4. FULL is completely specified, such as Tuesday, April 12, 1952 AD or 3:30:42pm PST

Setting Time Zones

You can set the time zone on the format. If you want more control over the format or parsing, cast the DateFormat you get from the factory methods to a SimpleDateFormat. This works for the majority of countries.

NoteRemember to check getDynamicClassID() before carrying out the cast.

Working with Positions

You can also use forms of the parse and format methods with ParsePosition and FieldPosition to enable you to:

  1. Progressively parse through pieces of a string.

  2. Align any particular field, or find out where it is for selection on the screen.

SimpleDateFormat

SimpleDateFormat is a concrete class used for formatting and parsing dates in a language-independent manner. It allows for formatting, parsing, and normalization. It formats or parses a date or time, which is the standard milliseconds since 24:00 GMT, Jan. 1, 1970.

SimpleDateFormat is the only built-in implementation of DateFormat. It provides a programmable interface that can be used to produce formatted dates and times in a wide variety of formats. The formats include almost all of the most common ones.

Create a date-time formatter using the following methods rather than constructing an instance of SimpleDateFormat. In this way, the program is guaranteed to get an appropriate formatting pattern of the locale.

  1. DateFormat::getInstance()

  2. getDateInstance()

  3. getDateTimeInstance()

If you need a more unusual pattern, construct a SimpleDateFormat directly and give it an appropriate pattern.

Date/Time Format Syntax

A date pattern is a string of characters, where specific strings of characters are replaced with date and time data from a calendar when formatting or used to generate data for a calendar when parsing.

The Date Field Symbol Table below contains the characters used in patterns to show the appropriate formats for a given locale, such as yyyy for the year. Characters may be used multiple times. For example, if y is used for the year, 'yy' might produce '99', whereas 'yyyy' produces '1999'. For most numerical fields, the number of characters specifies the field width. For example, if h is the hour, 'h' might produce '5', but 'hh' produces '05'. For some characters, the count specifies whether an abbreviated or full form should be used, but may have other choices, as given below.

Two single quotes represents a literal single quote, either inside or outside single quotes. Text within single quotes is not interpreted in any way (except for two adjacent single quotes). Otherwise all ASCII letter from a to z and A to Z are reserved as syntax characters, and require quoting if they are to represent literal characters. In addition, certain ASCII punctuation characters may become variable in the future (eg ":" being interpreted as the time separator and '/' as a date separator, and replaced by respective locale-sensitive characters in display).

"Stand Alone" values refer to those designed to stand on their own, as opposed to being with other formatted values. "2nd quarter" would use the stand alone format (QQQQ), whereas "2nd quarter 2007" would use the regular format (qqqq yyyy).

SymbolMeaningExample
Gera designatorGAD
yyearyy
yyyy or y
96
1996
Yyear of "Week of Year"Y1997
uextended yearu4601
QquarterQ or QQ
QQQ
QQQQ
02
Q2
2nd quarter
qStand Alone quarterq or qq
qqq
qqqq
02
Q2
2nd quarter
Mmonth in yearM or MM
MMM
MMMM
MMMMM
09
Sept
September
S
LStand Alone month in yearL or LL
LLL
LLLL
LLLLL
09
Sept
September
S
wweek of yearw or ww27
Wweek of monthW2
dday in monthd
dd
2
02
Dday of yearD189
Fday of week in month2 (2nd Wed in July)
gmodified julian dayg2451334
Eday of weekE, EE, or EEE
EEEE
EEEEE
Tues
Tuesday
T
elocal day of week
example: if Monday is 1st day, Tuesday is 2nd )
e or ee
eee
eeee
eeeee
2
Tues
Tuesday
T
cStand Alone local day of weeke or ee
eee
eeee
eeeee
2
Tues
Tuesday
T
aam/pm markerapm
hhour in am/pm (1~12)h
hh
7
07
Hhour in day (0~23)H
HH
0
00
khour in day (1~24)k
kk
24
24
Khour in am/pm (0~11)K
KK
0
00
mminute in hourm
mm
4
04
ssecond in minutes
ss
5
05
Smillisecond
rounds to count of letters)
S
SS
SSS
SSSS
2
24
235
2350
Amilliseconds in dayA61201235
zTime Zone: Names if available, otherwise the "location format" for generic times,
and the localized GMT format for standard or daylight times.
z, zz, or zzz
zzzz
PDT
Pacific Daylight Time
ZTime Zone: RFC 822
Time Zone: GMT offset
Z, ZZ, or ZZZ
ZZZZ
-0800
GMT-08:00
vTime Zone: Generic Time. Abbreviation or short name if available.v
vvvv
PT
Pacific Time or United States (Los Angeles)
VTime Zone: AbbreviationVPT
VVVVTime Zone: Location formatVVVVUnited States (Los Angeles)
Wweek in month2
'escape for text'(nothing)
' 'two single quotes produce one' ''

NoteAny characters in the pattern that are not in the ranges of ['a'..'z'] and ['A'..'Z'] will be treated as quoted text. For instance, characters like ':', '.', ' ', '#' and '@' will appear in the resulting time text even they are not enclosed within single quotes.The single quote is used to 'escape' letters. Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote.
A pattern containing any invalid pattern letter results in a failing UErrorCode result during formatting or parsing.
Format PatternResult

yyyy.MM.dd G 'at' HH:mm:ss zzz

1996.07.10 AD at 15:08:56 PDT

EEE, MMM d, ''yy

Wed, July 10, '96

h:mm a

12:08 PM

hh 'o''clock' a, zzzz

12 o'clock PM, Pacific Daylight Time

K:mm a, z

0:00 PM, PST

yyyyy.MMMM.dd GGG hh:mm aaa

01996.July.10 AD 12:08 PM

DateFormatSymbols

DateFormatSymbols is a public class for encapsulating localizable date-time formatting data, including time zone data. DateFormatSymbols is used by DateFormat and SimpleDateFormat.

DateFormatSymbols specifies the exact character strings to use for various parts of a date or time For example, the names of the months and days of the week, the strings for AM and PM and the day of the week considered to be the first day of the week (used in drawing calendar grids) are controlled by DateFormatSymbols.

Create a date-time formatter using the createTimeInstance, createDateInstance, or createDateTimeInstance methods in DateFormat. Each of these methods can return a date/time formatter initialized with a default format pattern, along with the date-time formatting data for a given or default locale. After a formatter is created, modify the format pattern using applyPattern.

If you want to create a date-time formatter with a particular format pattern and locale, use one of the SimpleDateFormat constructors:

UnicodeString aPattern("GyyyyMMddHHmmssSSZ", "");
new SimpleDateFormat(aPattern, new DateFormatSymbols(Locale::getUS())

This loads the appropriate date-time formatting data from the locale.s

Programming Examples

See date and time formatting examples .



Copyright (c) 2000 - 2007 IBM and Others - PDF Version - Feedback: http://icu-project.org/contacts.html

User Guide for ICU v3.8 Generated 2007-09-14.