2 ********************************************************************************
3 * Copyright (C) 1997-2008, International Business Machines
4 * Corporation and others. All Rights Reserved.
5 ********************************************************************************
9 * Modification History:
11 * Date Name Description
12 * 02/19/97 aliu Converted from java.
13 * 04/01/97 aliu Added support for centuries.
14 * 07/23/98 stephen JDK 1.2 sync
15 * 11/15/99 weiv Added support for week of year/day of week formatting
16 ********************************************************************************
22 #include "unicode/utypes.h"
24 #if !UCONFIG_NO_FORMATTING
26 #include "unicode/udat.h"
27 #include "unicode/calendar.h"
28 #include "unicode/numfmt.h"
29 #include "unicode/format.h"
30 #include "unicode/locid.h"
34 * \brief C++ API: Abstract class for converting dates.
42 * DateFormat is an abstract class for a family of classes that convert dates and
43 * times from their internal representations to textual form and back again in a
44 * language-independent manner. Converting from the internal representation (milliseconds
45 * since midnight, January 1, 1970) to text is known as "formatting," and converting
46 * from text to millis is known as "parsing." We currently define only one concrete
47 * subclass of DateFormat: SimpleDateFormat, which can handle pretty much all normal
48 * date formatting and parsing actions.
50 * DateFormat helps you to format and parse dates for any locale. Your code can
51 * be completely independent of the locale conventions for months, days of the
52 * week, or even the calendar format: lunar vs. solar.
54 * To format a date for the current Locale, use one of the static factory
58 * DateFormat* dfmt = DateFormat::createDateInstance();
59 * UDate myDate = Calendar::getNow();
60 * UnicodeString myString;
61 * myString = dfmt->format( myDate, myString );
64 * If you are formatting multiple numbers, it is more efficient to get the
65 * format and use it multiple times so that the system doesn't have to fetch the
66 * information about the local language and country conventions multiple times.
69 * DateFormat* df = DateFormat::createDateInstance();
70 * UnicodeString myString;
71 * UDate myDateArr[] = { 0.0, 100000000.0, 2000000000.0 }; // test values
72 * for (int32_t i = 0; i < 3; ++i) {
74 * cout << df->format( myDateArr[i], myString ) << endl;
78 * To get specific fields of a date, you can use UFieldPosition to
79 * get specific fields.
82 * DateFormat* dfmt = DateFormat::createDateInstance();
83 * FieldPosition pos(DateFormat::YEAR_FIELD);
84 * UnicodeString myString;
85 * myString = dfmt->format( myDate, myString );
86 * cout << myString << endl;
87 * cout << pos.getBeginIndex() << "," << pos. getEndIndex() << endl;
90 * To format a date for a different Locale, specify it in the call to
91 * createDateInstance().
95 * DateFormat::createDateInstance( DateFormat::SHORT, Locale::getFrance());
98 * You can use a DateFormat to parse also.
101 * UErrorCode status = U_ZERO_ERROR;
102 * UDate myDate = df->parse(myString, status);
105 * Use createDateInstance() to produce the normal date format for that country.
106 * There are other static factory methods available. Use createTimeInstance()
107 * to produce the normal time format for that country. Use createDateTimeInstance()
108 * to produce a DateFormat that formats both date and time. You can pass in
109 * different options to these factory methods to control the length of the
110 * result; from SHORT to MEDIUM to LONG to FULL. The exact result depends on the
111 * locale, but generally:
113 * <li> SHORT is completely numeric, such as 12/13/52 or 3:30pm
114 * <li> MEDIUM is longer, such as Jan 12, 1952
115 * <li> LONG is longer, such as January 12, 1952 or 3:30:32pm
116 * <li> FULL is pretty completely specified, such as
117 * Tuesday, April 12, 1952 AD or 3:30:42pm PST.
119 * You can also set the time zone on the format if you wish. If you want even
120 * more control over the format or parsing, (or want to give your users more
121 * control), you can try casting the DateFormat you get from the factory methods
122 * to a SimpleDateFormat. This will work for the majority of countries; just
123 * remember to chck getDynamicClassID() before carrying out the cast.
125 * You can also use forms of the parse and format methods with ParsePosition and
126 * FieldPosition to allow you to
128 * <li> Progressively parse through pieces of a string.
129 * <li> Align any particular field, or find out where it is for selection
133 * <p><em>User subclasses are not supported.</em> While clients may write
134 * subclasses, such code will not necessarily work and will not be
135 * guaranteed to work stably from release to release.
137 class U_I18N_API DateFormat
: public Format
{
141 * Constants for various style patterns. These reflect the order of items in
142 * the DateTimePatterns resource. There are 4 time patterns, 4 date patterns,
143 * and then the date-time pattern. Each block of 4 values in the resource occurs
144 * in the order full, long, medium, short.
156 kDateOffset
= kShort
+ 1,
157 // kFull + kDateOffset = 4
158 // kLong + kDateOffset = 5
159 // kMedium + kDateOffset = 6
160 // kShort + kDateOffset = 7
166 kRelative
= (1 << 7),
168 kFullRelative
= (kFull
| kRelative
),
170 kLongRelative
= kLong
| kRelative
,
172 kMediumRelative
= kMedium
| kRelative
,
174 kShortRelative
= kShort
| kRelative
,
182 * These constants are provided for backwards compatibility only.
183 * Please use the C++ style constants defined above.
190 DATE_OFFSET
= kDateOffset
,
192 DATE_TIME
= kDateTime
199 virtual ~DateFormat();
202 * Equality operator. Returns true if the two formats have the same behavior.
205 virtual UBool
operator==(const Format
&) const;
208 * Format an object to produce a string. This method handles Formattable
209 * objects with a UDate type. If a the Formattable object type is not a Date,
210 * then it returns a failing UErrorCode.
212 * @param obj The object to format. Must be a Date.
213 * @param appendTo Output parameter to receive result.
214 * Result is appended to existing contents.
215 * @param pos On input: an alignment field, if desired.
216 * On output: the offsets of the alignment field.
217 * @param status Output param filled with success/failure status.
218 * @return Reference to 'appendTo' parameter.
221 virtual UnicodeString
& format(const Formattable
& obj
,
222 UnicodeString
& appendTo
,
224 UErrorCode
& status
) const;
227 * Formats a date into a date/time string. This is an abstract method which
228 * concrete subclasses must implement.
230 * On input, the FieldPosition parameter may have its "field" member filled with
231 * an enum value specifying a field. On output, the FieldPosition will be filled
232 * in with the text offsets for that field.
233 * <P> For example, given a time text
234 * "1996.07.10 AD at 15:08:56 PDT", if the given fieldPosition.field is
235 * UDAT_YEAR_FIELD, the offsets fieldPosition.beginIndex and
236 * statfieldPositionus.getEndIndex will be set to 0 and 4, respectively.
238 * that if the same time field appears more than once in a pattern, the status will
239 * be set for the first occurence of that time field. For instance,
240 * formatting a UDate to the time string "1 PM PDT (Pacific Daylight Time)"
241 * using the pattern "h a z (zzzz)" and the alignment field
242 * DateFormat::TIMEZONE_FIELD, the offsets fieldPosition.beginIndex and
243 * fieldPosition.getEndIndex will be set to 5 and 8, respectively, for the first
244 * occurence of the timezone pattern character 'z'.
246 * @param cal Calendar set to the date and time to be formatted
247 * into a date/time string.
248 * @param appendTo Output parameter to receive result.
249 * Result is appended to existing contents.
250 * @param fieldPosition On input: an alignment field, if desired (see examples above)
251 * On output: the offsets of the alignment field (see examples above)
252 * @return Reference to 'appendTo' parameter.
255 virtual UnicodeString
& format( Calendar
& cal
,
256 UnicodeString
& appendTo
,
257 FieldPosition
& fieldPosition
) const = 0;
260 * Formats a UDate into a date/time string.
262 * On input, the FieldPosition parameter may have its "field" member filled with
263 * an enum value specifying a field. On output, the FieldPosition will be filled
264 * in with the text offsets for that field.
265 * <P> For example, given a time text
266 * "1996.07.10 AD at 15:08:56 PDT", if the given fieldPosition.field is
267 * UDAT_YEAR_FIELD, the offsets fieldPosition.beginIndex and
268 * statfieldPositionus.getEndIndex will be set to 0 and 4, respectively.
270 * that if the same time field appears more than once in a pattern, the status will
271 * be set for the first occurence of that time field. For instance,
272 * formatting a UDate to the time string "1 PM PDT (Pacific Daylight Time)"
273 * using the pattern "h a z (zzzz)" and the alignment field
274 * DateFormat::TIMEZONE_FIELD, the offsets fieldPosition.beginIndex and
275 * fieldPosition.getEndIndex will be set to 5 and 8, respectively, for the first
276 * occurence of the timezone pattern character 'z'.
278 * @param date UDate to be formatted into a date/time string.
279 * @param appendTo Output parameter to receive result.
280 * Result is appended to existing contents.
281 * @param fieldPosition On input: an alignment field, if desired (see examples above)
282 * On output: the offsets of the alignment field (see examples above)
283 * @return Reference to 'appendTo' parameter.
286 UnicodeString
& format( UDate date
,
287 UnicodeString
& appendTo
,
288 FieldPosition
& fieldPosition
) const;
291 * Formats a UDate into a date/time string. If there is a problem, you won't
292 * know, using this method. Use the overloaded format() method which takes a
293 * FieldPosition& to detect formatting problems.
295 * @param date The UDate value to be formatted into a string.
296 * @param appendTo Output parameter to receive result.
297 * Result is appended to existing contents.
298 * @return Reference to 'appendTo' parameter.
301 UnicodeString
& format(UDate date
, UnicodeString
& appendTo
) const;
304 * Redeclared Format method.
306 * @param obj The object to be formatted into a string.
307 * @param appendTo Output parameter to receive result.
308 * Result is appended to existing contents.
309 * @param status Output param filled with success/failure status.
310 * @return Reference to 'appendTo' parameter.
313 UnicodeString
& format(const Formattable
& obj
,
314 UnicodeString
& appendTo
,
315 UErrorCode
& status
) const;
318 * Parse a date/time string.
320 * @param text The string to be parsed into a UDate value.
321 * @param status Output param to be set to success/failure code. If
322 * 'text' cannot be parsed, it will be set to a failure
324 * @result The parsed UDate value, if successful.
327 virtual UDate
parse( const UnicodeString
& text
,
328 UErrorCode
& status
) const;
331 * Parse a date/time string beginning at the given parse position. For
332 * example, a time text "07/10/96 4:5 PM, PDT" will be parsed into a Date
333 * that is equivalent to Date(837039928046).
335 * By default, parsing is lenient: If the input is not in the form used by
336 * this object's format method but can still be parsed as a date, then the
337 * parse succeeds. Clients may insist on strict adherence to the format by
338 * calling setLenient(false).
340 * @see DateFormat::setLenient(boolean)
342 * @param text The date/time string to be parsed
343 * @param cal a Calendar set to the date and time to be formatted
344 * into a date/time string.
345 * @param pos On input, the position at which to start parsing; on
346 * output, the position at which parsing terminated, or the
347 * start position if the parse failed.
348 * @return A valid UDate if the input could be parsed.
351 virtual void parse( const UnicodeString
& text
,
353 ParsePosition
& pos
) const = 0;
356 * Parse a date/time string beginning at the given parse position. For
357 * example, a time text "07/10/96 4:5 PM, PDT" will be parsed into a Date
358 * that is equivalent to Date(837039928046).
360 * By default, parsing is lenient: If the input is not in the form used by
361 * this object's format method but can still be parsed as a date, then the
362 * parse succeeds. Clients may insist on strict adherence to the format by
363 * calling setLenient(false).
365 * @see DateFormat::setLenient(boolean)
367 * @param text The date/time string to be parsed
368 * @param pos On input, the position at which to start parsing; on
369 * output, the position at which parsing terminated, or the
370 * start position if the parse failed.
371 * @return A valid UDate if the input could be parsed.
374 UDate
parse( const UnicodeString
& text
,
375 ParsePosition
& pos
) const;
378 * Parse a string to produce an object. This methods handles parsing of
379 * date/time strings into Formattable objects with UDate types.
381 * Before calling, set parse_pos.index to the offset you want to start
382 * parsing at in the source. After calling, parse_pos.index is the end of
383 * the text you parsed. If error occurs, index is unchanged.
385 * When parsing, leading whitespace is discarded (with a successful parse),
386 * while trailing whitespace is left as is.
388 * See Format::parseObject() for more.
390 * @param source The string to be parsed into an object.
391 * @param result Formattable to be set to the parse result.
392 * If parse fails, return contents are undefined.
393 * @param parse_pos The position to start parsing at. Upon return
394 * this param is set to the position after the
395 * last character successfully parsed. If the
396 * source is not parsed successfully, this param
397 * will remain unchanged.
398 * @return A newly created Formattable* object, or NULL
399 * on failure. The caller owns this and should
400 * delete it when done.
403 virtual void parseObject(const UnicodeString
& source
,
405 ParsePosition
& parse_pos
) const;
408 * Create a default date/time formatter that uses the SHORT style for both
409 * the date and the time.
411 * @return A date/time formatter which the caller owns.
414 static DateFormat
* U_EXPORT2
createInstance(void);
417 * This is for ICU internal use only. Please do not use.
418 * Create a date/time formatter from skeleton and a given locale.
420 * Users are encouraged to use the skeleton macros defined in udat.h.
421 * For example, MONTH_WEEKDAY_DAY, which is "MMMMEEEEd",
422 * and which means the pattern should have day, month, and day-of-week
423 * fields, and follow the long date format defined in date time pattern.
424 * For example, for English, the full pattern should be
427 * Temporarily, this is an internal API, used by DateIntevalFormat only.
428 * There will be a new set of APIs for the same purpose coming soon.
429 * After which, this API will be replaced.
431 * @param skeleton the skeleton on which date format based.
432 * @param locale the given locale.
433 * @param status Output param to be set to success/failure code.
434 * If it is failure, the returned date formatter will
436 * @return a simple date formatter which the caller owns.
439 static DateFormat
* U_EXPORT2
createPatternInstance(
440 const UnicodeString
& skeleton
,
441 const Locale
& locale
,
445 * Creates a time formatter with the given formatting style for the given
448 * @param style The given formatting style. For example,
449 * SHORT for "h:mm a" in the US locale.
450 * @param aLocale The given locale.
451 * @return A time formatter which the caller owns.
454 static DateFormat
* U_EXPORT2
createTimeInstance(EStyle style
= kDefault
,
455 const Locale
& aLocale
= Locale::getDefault());
458 * Creates a date formatter with the given formatting style for the given
461 * @param style The given formatting style. For example,
462 * SHORT for "M/d/yy" in the US locale.
463 * @param aLocale The given locale.
464 * @return A date formatter which the caller owns.
467 static DateFormat
* U_EXPORT2
createDateInstance(EStyle style
= kDefault
,
468 const Locale
& aLocale
= Locale::getDefault());
471 * Creates a date/time formatter with the given formatting styles for the
474 * @param dateStyle The given formatting style for the date portion of the result.
475 * For example, SHORT for "M/d/yy" in the US locale.
476 * @param timeStyle The given formatting style for the time portion of the result.
477 * For example, SHORT for "h:mm a" in the US locale.
478 * @param aLocale The given locale.
479 * @return A date/time formatter which the caller owns.
482 static DateFormat
* U_EXPORT2
createDateTimeInstance(EStyle dateStyle
= kDefault
,
483 EStyle timeStyle
= kDefault
,
484 const Locale
& aLocale
= Locale::getDefault());
487 * Gets the set of locales for which DateFormats are installed.
488 * @param count Filled in with the number of locales in the list that is returned.
489 * @return the set of locales for which DateFormats are installed. The caller
490 * does NOT own this list and must not delete it.
493 static const Locale
* U_EXPORT2
getAvailableLocales(int32_t& count
);
496 * Returns true if the formatter is set for lenient parsing.
499 virtual UBool
isLenient(void) const;
502 * Specify whether or not date/time parsing is to be lenient. With lenient
503 * parsing, the parser may use heuristics to interpret inputs that do not
504 * precisely match this object's format. With strict parsing, inputs must
505 * match this object's format.
507 * @param lenient True specifies date/time interpretation to be lenient.
508 * @see Calendar::setLenient
511 virtual void setLenient(UBool lenient
);
514 * Gets the calendar associated with this date/time formatter.
515 * @return the calendar associated with this date/time formatter.
518 virtual const Calendar
* getCalendar(void) const;
521 * Set the calendar to be used by this date format. Initially, the default
522 * calendar for the specified or default locale is used. The caller should
523 * not delete the Calendar object after it is adopted by this call.
524 * Adopting a new calendar will change to the default symbols.
526 * @param calendarToAdopt Calendar object to be adopted.
529 virtual void adoptCalendar(Calendar
* calendarToAdopt
);
532 * Set the calendar to be used by this date format. Initially, the default
533 * calendar for the specified or default locale is used.
535 * @param newCalendar Calendar object to be set.
538 virtual void setCalendar(const Calendar
& newCalendar
);
542 * Gets the number formatter which this date/time formatter uses to format
543 * and parse the numeric portions of the pattern.
544 * @return the number formatter which this date/time formatter uses.
547 virtual const NumberFormat
* getNumberFormat(void) const;
550 * Allows you to set the number formatter. The caller should
551 * not delete the NumberFormat object after it is adopted by this call.
552 * @param formatToAdopt NumberFormat object to be adopted.
555 virtual void adoptNumberFormat(NumberFormat
* formatToAdopt
);
558 * Allows you to set the number formatter.
559 * @param newNumberFormat NumberFormat object to be set.
562 virtual void setNumberFormat(const NumberFormat
& newNumberFormat
);
565 * Returns a reference to the TimeZone used by this DateFormat's calendar.
566 * @return the time zone associated with the calendar of DateFormat.
569 virtual const TimeZone
& getTimeZone(void) const;
572 * Sets the time zone for the calendar of this DateFormat object. The caller
573 * no longer owns the TimeZone object and should not delete it after this call.
574 * @param zoneToAdopt the TimeZone to be adopted.
577 virtual void adoptTimeZone(TimeZone
* zoneToAdopt
);
580 * Sets the time zone for the calendar of this DateFormat object.
581 * @param zone the new time zone.
584 virtual void setTimeZone(const TimeZone
& zone
);
588 * Default constructor. Creates a DateFormat with no Calendar or NumberFormat
589 * associated with it. This constructor depends on the subclasses to fill in
590 * the calendar and numberFormat fields.
599 DateFormat(const DateFormat
&);
602 * Default assignment operator.
605 DateFormat
& operator=(const DateFormat
&);
608 * The calendar that DateFormat uses to produce the time field values needed
609 * to implement date/time formatting. Subclasses should generally initialize
610 * this to the default calendar for the locale associated with this DateFormat.
616 * The number formatter that DateFormat uses to format numbers in dates and
617 * times. Subclasses should generally initialize this to the default number
618 * format for the locale associated with this DateFormat.
621 NumberFormat
* fNumberFormat
;
625 * Gets the date/time formatter with the given formatting styles for the
627 * @param dateStyle the given date formatting style.
628 * @param timeStyle the given time formatting style.
629 * @param inLocale the given locale.
630 * @return a date/time formatter, or 0 on failure.
632 static DateFormat
* U_EXPORT2
create(EStyle timeStyle
, EStyle dateStyle
, const Locale
&);
636 * Field selector for FieldPosition for DateFormat fields.
637 * @obsolete ICU 3.4 use UDateFormatField instead, since this API will be
638 * removed in that release
642 // Obsolete; use UDateFormatField instead
643 kEraField
= UDAT_ERA_FIELD
,
644 kYearField
= UDAT_YEAR_FIELD
,
645 kMonthField
= UDAT_MONTH_FIELD
,
646 kDateField
= UDAT_DATE_FIELD
,
647 kHourOfDay1Field
= UDAT_HOUR_OF_DAY1_FIELD
,
648 kHourOfDay0Field
= UDAT_HOUR_OF_DAY0_FIELD
,
649 kMinuteField
= UDAT_MINUTE_FIELD
,
650 kSecondField
= UDAT_SECOND_FIELD
,
651 kMillisecondField
= UDAT_FRACTIONAL_SECOND_FIELD
,
652 kDayOfWeekField
= UDAT_DAY_OF_WEEK_FIELD
,
653 kDayOfYearField
= UDAT_DAY_OF_YEAR_FIELD
,
654 kDayOfWeekInMonthField
= UDAT_DAY_OF_WEEK_IN_MONTH_FIELD
,
655 kWeekOfYearField
= UDAT_WEEK_OF_YEAR_FIELD
,
656 kWeekOfMonthField
= UDAT_WEEK_OF_MONTH_FIELD
,
657 kAmPmField
= UDAT_AM_PM_FIELD
,
658 kHour1Field
= UDAT_HOUR1_FIELD
,
659 kHour0Field
= UDAT_HOUR0_FIELD
,
660 kTimezoneField
= UDAT_TIMEZONE_FIELD
,
661 kYearWOYField
= UDAT_YEAR_WOY_FIELD
,
662 kDOWLocalField
= UDAT_DOW_LOCAL_FIELD
,
663 kExtendedYearField
= UDAT_EXTENDED_YEAR_FIELD
,
664 kJulianDayField
= UDAT_JULIAN_DAY_FIELD
,
665 kMillisecondsInDayField
= UDAT_MILLISECONDS_IN_DAY_FIELD
,
667 // Obsolete; use UDateFormatField instead
668 ERA_FIELD
= UDAT_ERA_FIELD
,
669 YEAR_FIELD
= UDAT_YEAR_FIELD
,
670 MONTH_FIELD
= UDAT_MONTH_FIELD
,
671 DATE_FIELD
= UDAT_DATE_FIELD
,
672 HOUR_OF_DAY1_FIELD
= UDAT_HOUR_OF_DAY1_FIELD
,
673 HOUR_OF_DAY0_FIELD
= UDAT_HOUR_OF_DAY0_FIELD
,
674 MINUTE_FIELD
= UDAT_MINUTE_FIELD
,
675 SECOND_FIELD
= UDAT_SECOND_FIELD
,
676 MILLISECOND_FIELD
= UDAT_FRACTIONAL_SECOND_FIELD
,
677 DAY_OF_WEEK_FIELD
= UDAT_DAY_OF_WEEK_FIELD
,
678 DAY_OF_YEAR_FIELD
= UDAT_DAY_OF_YEAR_FIELD
,
679 DAY_OF_WEEK_IN_MONTH_FIELD
= UDAT_DAY_OF_WEEK_IN_MONTH_FIELD
,
680 WEEK_OF_YEAR_FIELD
= UDAT_WEEK_OF_YEAR_FIELD
,
681 WEEK_OF_MONTH_FIELD
= UDAT_WEEK_OF_MONTH_FIELD
,
682 AM_PM_FIELD
= UDAT_AM_PM_FIELD
,
683 HOUR1_FIELD
= UDAT_HOUR1_FIELD
,
684 HOUR0_FIELD
= UDAT_HOUR0_FIELD
,
685 TIMEZONE_FIELD
= UDAT_TIMEZONE_FIELD
689 inline UnicodeString
&
690 DateFormat::format(const Formattable
& obj
,
691 UnicodeString
& appendTo
,
692 UErrorCode
& status
) const {
693 return Format::format(obj
, appendTo
, status
);
697 #endif /* #if !UCONFIG_NO_FORMATTING */