2 ********************************************************************************
3 * Copyright (C) 1997-2005, 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
169 * These constants are provided for backwards compatibility only.
170 * Please use the C++ style constants defined above.
177 DATE_OFFSET
= kDateOffset
,
179 DATE_TIME
= kDateTime
186 virtual ~DateFormat();
189 * Equality operator. Returns true if the two formats have the same behavior.
192 virtual UBool
operator==(const Format
&) const;
195 * Format an object to produce a string. This method handles Formattable
196 * objects with a UDate type. If a the Formattable object type is not a Date,
197 * then it returns a failing UErrorCode.
199 * @param obj The object to format. Must be a Date.
200 * @param appendTo Output parameter to receive result.
201 * Result is appended to existing contents.
202 * @param pos On input: an alignment field, if desired.
203 * On output: the offsets of the alignment field.
204 * @param status Output param filled with success/failure status.
205 * @return Reference to 'appendTo' parameter.
208 virtual UnicodeString
& format(const Formattable
& obj
,
209 UnicodeString
& appendTo
,
211 UErrorCode
& status
) const;
214 * Formats a date into a date/time string. This is an abstract method which
215 * concrete subclasses must implement.
217 * On input, the FieldPosition parameter may have its "field" member filled with
218 * an enum value specifying a field. On output, the FieldPosition will be filled
219 * in with the text offsets for that field.
220 * <P> For example, given a time text
221 * "1996.07.10 AD at 15:08:56 PDT", if the given fieldPosition.field is
222 * UDAT_YEAR_FIELD, the offsets fieldPosition.beginIndex and
223 * statfieldPositionus.getEndIndex will be set to 0 and 4, respectively.
225 * that if the same time field appears more than once in a pattern, the status will
226 * be set for the first occurence of that time field. For instance,
227 * formatting a UDate to the time string "1 PM PDT (Pacific Daylight Time)"
228 * using the pattern "h a z (zzzz)" and the alignment field
229 * DateFormat::TIMEZONE_FIELD, the offsets fieldPosition.beginIndex and
230 * fieldPosition.getEndIndex will be set to 5 and 8, respectively, for the first
231 * occurence of the timezone pattern character 'z'.
233 * @param cal Calendar set to the date and time to be formatted
234 * into a date/time string.
235 * @param appendTo Output parameter to receive result.
236 * Result is appended to existing contents.
237 * @param fieldPosition On input: an alignment field, if desired (see examples above)
238 * On output: the offsets of the alignment field (see examples above)
239 * @return Reference to 'appendTo' parameter.
242 virtual UnicodeString
& format( Calendar
& cal
,
243 UnicodeString
& appendTo
,
244 FieldPosition
& fieldPosition
) const = 0;
247 * Formats a UDate into a date/time string.
249 * On input, the FieldPosition parameter may have its "field" member filled with
250 * an enum value specifying a field. On output, the FieldPosition will be filled
251 * in with the text offsets for that field.
252 * <P> For example, given a time text
253 * "1996.07.10 AD at 15:08:56 PDT", if the given fieldPosition.field is
254 * UDAT_YEAR_FIELD, the offsets fieldPosition.beginIndex and
255 * statfieldPositionus.getEndIndex will be set to 0 and 4, respectively.
257 * that if the same time field appears more than once in a pattern, the status will
258 * be set for the first occurence of that time field. For instance,
259 * formatting a UDate to the time string "1 PM PDT (Pacific Daylight Time)"
260 * using the pattern "h a z (zzzz)" and the alignment field
261 * DateFormat::TIMEZONE_FIELD, the offsets fieldPosition.beginIndex and
262 * fieldPosition.getEndIndex will be set to 5 and 8, respectively, for the first
263 * occurence of the timezone pattern character 'z'.
265 * @param date UDate to be formatted into a date/time string.
266 * @param appendTo Output parameter to receive result.
267 * Result is appended to existing contents.
268 * @param fieldPosition On input: an alignment field, if desired (see examples above)
269 * On output: the offsets of the alignment field (see examples above)
270 * @return Reference to 'appendTo' parameter.
273 UnicodeString
& format( UDate date
,
274 UnicodeString
& appendTo
,
275 FieldPosition
& fieldPosition
) const;
278 * Formats a UDate into a date/time string. If there is a problem, you won't
279 * know, using this method. Use the overloaded format() method which takes a
280 * FieldPosition& to detect formatting problems.
282 * @param date The UDate value to be formatted into a string.
283 * @param appendTo Output parameter to receive result.
284 * Result is appended to existing contents.
285 * @return Reference to 'appendTo' parameter.
288 UnicodeString
& format(UDate date
, UnicodeString
& appendTo
) const;
291 * Redeclared Format method.
293 * @param obj The object to be formatted into a string.
294 * @param appendTo Output parameter to receive result.
295 * Result is appended to existing contents.
296 * @param status Output param filled with success/failure status.
297 * @return Reference to 'appendTo' parameter.
300 UnicodeString
& format(const Formattable
& obj
,
301 UnicodeString
& appendTo
,
302 UErrorCode
& status
) const;
305 * Parse a date/time string.
307 * @param text The string to be parsed into a UDate value.
308 * @param status Output param to be set to success/failure code. If
309 * 'text' cannot be parsed, it will be set to a failure
311 * @result The parsed UDate value, if successful.
314 virtual UDate
parse( const UnicodeString
& text
,
315 UErrorCode
& status
) const;
318 * Parse a date/time string beginning at the given parse position. For
319 * example, a time text "07/10/96 4:5 PM, PDT" will be parsed into a Date
320 * that is equivalent to Date(837039928046).
322 * By default, parsing is lenient: If the input is not in the form used by
323 * this object's format method but can still be parsed as a date, then the
324 * parse succeeds. Clients may insist on strict adherence to the format by
325 * calling setLenient(false).
327 * @see DateFormat::setLenient(boolean)
329 * @param text The date/time string to be parsed
330 * @param cal a Calendar set to the date and time to be formatted
331 * into a date/time string.
332 * @param pos On input, the position at which to start parsing; on
333 * output, the position at which parsing terminated, or the
334 * start position if the parse failed.
335 * @return A valid UDate if the input could be parsed.
338 virtual void parse( const UnicodeString
& text
,
340 ParsePosition
& pos
) const = 0;
343 * Parse a date/time string beginning at the given parse position. For
344 * example, a time text "07/10/96 4:5 PM, PDT" will be parsed into a Date
345 * that is equivalent to Date(837039928046).
347 * By default, parsing is lenient: If the input is not in the form used by
348 * this object's format method but can still be parsed as a date, then the
349 * parse succeeds. Clients may insist on strict adherence to the format by
350 * calling setLenient(false).
352 * @see DateFormat::setLenient(boolean)
354 * @param text The date/time string to be parsed
355 * @param pos On input, the position at which to start parsing; on
356 * output, the position at which parsing terminated, or the
357 * start position if the parse failed.
358 * @return A valid UDate if the input could be parsed.
361 UDate
parse( const UnicodeString
& text
,
362 ParsePosition
& pos
) const;
365 * Parse a string to produce an object. This methods handles parsing of
366 * date/time strings into Formattable objects with UDate types.
368 * Before calling, set parse_pos.index to the offset you want to start
369 * parsing at in the source. After calling, parse_pos.index is the end of
370 * the text you parsed. If error occurs, index is unchanged.
372 * When parsing, leading whitespace is discarded (with a successful parse),
373 * while trailing whitespace is left as is.
375 * See Format::parseObject() for more.
377 * @param source The string to be parsed into an object.
378 * @param result Formattable to be set to the parse result.
379 * If parse fails, return contents are undefined.
380 * @param parse_pos The position to start parsing at. Upon return
381 * this param is set to the position after the
382 * last character successfully parsed. If the
383 * source is not parsed successfully, this param
384 * will remain unchanged.
385 * @return A newly created Formattable* object, or NULL
386 * on failure. The caller owns this and should
387 * delete it when done.
390 virtual void parseObject(const UnicodeString
& source
,
392 ParsePosition
& parse_pos
) const;
395 * Create a default date/time formatter that uses the SHORT style for both
396 * the date and the time.
398 * @return A date/time formatter which the caller owns.
401 static DateFormat
* U_EXPORT2
createInstance(void);
404 * Creates a time formatter with the given formatting style for the given
407 * @param style The given formatting style. For example,
408 * SHORT for "h:mm a" in the US locale.
409 * @param aLocale The given locale.
410 * @return A time formatter which the caller owns.
413 static DateFormat
* U_EXPORT2
createTimeInstance(EStyle style
= kDefault
,
414 const Locale
& aLocale
= Locale::getDefault());
417 * Creates a date formatter with the given formatting style for the given
420 * @param style The given formatting style. For example,
421 * SHORT for "M/d/yy" in the US locale.
422 * @param aLocale The given locale.
423 * @return A date formatter which the caller owns.
426 static DateFormat
* U_EXPORT2
createDateInstance(EStyle style
= kDefault
,
427 const Locale
& aLocale
= Locale::getDefault());
430 * Creates a date/time formatter with the given formatting styles for the
433 * @param dateStyle The given formatting style for the date portion of the result.
434 * For example, SHORT for "M/d/yy" in the US locale.
435 * @param timeStyle The given formatting style for the time portion of the result.
436 * For example, SHORT for "h:mm a" in the US locale.
437 * @param aLocale The given locale.
438 * @return A date/time formatter which the caller owns.
441 static DateFormat
* U_EXPORT2
createDateTimeInstance(EStyle dateStyle
= kDefault
,
442 EStyle timeStyle
= kDefault
,
443 const Locale
& aLocale
= Locale::getDefault());
446 * Gets the set of locales for which DateFormats are installed.
447 * @param count Filled in with the number of locales in the list that is returned.
448 * @return the set of locales for which DateFormats are installed. The caller
449 * does NOT own this list and must not delete it.
452 static const Locale
* U_EXPORT2
getAvailableLocales(int32_t& count
);
455 * Returns true if the formatter is set for lenient parsing.
458 virtual UBool
isLenient(void) const;
461 * Specify whether or not date/time parsing is to be lenient. With lenient
462 * parsing, the parser may use heuristics to interpret inputs that do not
463 * precisely match this object's format. With strict parsing, inputs must
464 * match this object's format.
466 * @param lenient True specifies date/time interpretation to be lenient.
467 * @see Calendar::setLenient
470 virtual void setLenient(UBool lenient
);
473 * Gets the calendar associated with this date/time formatter.
474 * @return the calendar associated with this date/time formatter.
477 virtual const Calendar
* getCalendar(void) const;
480 * Set the calendar to be used by this date format. Initially, the default
481 * calendar for the specified or default locale is used. The caller should
482 * not delete the Calendar object after it is adopted by this call.
483 * Adopting a new calendar will change to the default symbols.
485 * @param calendarToAdopt Calendar object to be adopted.
488 virtual void adoptCalendar(Calendar
* calendarToAdopt
);
491 * Set the calendar to be used by this date format. Initially, the default
492 * calendar for the specified or default locale is used.
494 * @param newCalendar Calendar object to be set.
497 virtual void setCalendar(const Calendar
& newCalendar
);
501 * Gets the number formatter which this date/time formatter uses to format
502 * and parse the numeric portions of the pattern.
503 * @return the number formatter which this date/time formatter uses.
506 virtual const NumberFormat
* getNumberFormat(void) const;
509 * Allows you to set the number formatter. The caller should
510 * not delete the NumberFormat object after it is adopted by this call.
511 * @param formatToAdopt NumberFormat object to be adopted.
514 virtual void adoptNumberFormat(NumberFormat
* formatToAdopt
);
517 * Allows you to set the number formatter.
518 * @param newNumberFormat NumberFormat object to be set.
521 virtual void setNumberFormat(const NumberFormat
& newNumberFormat
);
524 * Returns a reference to the TimeZone used by this DateFormat's calendar.
525 * @return the time zone associated with the calendar of DateFormat.
528 virtual const TimeZone
& getTimeZone(void) const;
531 * Sets the time zone for the calendar of this DateFormat object. The caller
532 * no longer owns the TimeZone object and should not delete it after this call.
533 * @param zoneToAdopt the TimeZone to be adopted.
536 virtual void adoptTimeZone(TimeZone
* zoneToAdopt
);
539 * Sets the time zone for the calendar of this DateFormat object.
540 * @param zone the new time zone.
543 virtual void setTimeZone(const TimeZone
& zone
);
547 * Default constructor. Creates a DateFormat with no Calendar or NumberFormat
548 * associated with it. This constructor depends on the subclasses to fill in
549 * the calendar and numberFormat fields.
558 DateFormat(const DateFormat
&);
561 * Default assignment operator.
564 DateFormat
& operator=(const DateFormat
&);
567 * The calendar that DateFormat uses to produce the time field values needed
568 * to implement date/time formatting. Subclasses should generally initialize
569 * this to the default calendar for the locale associated with this DateFormat.
575 * The number formatter that DateFormat uses to format numbers in dates and
576 * times. Subclasses should generally initialize this to the default number
577 * format for the locale associated with this DateFormat.
580 NumberFormat
* fNumberFormat
;
584 * Gets the date/time formatter with the given formatting styles for the
586 * @param dateStyle the given date formatting style.
587 * @param timeStyle the given time formatting style.
588 * @param inLocale the given locale.
589 * @return a date/time formatter, or 0 on failure.
591 static DateFormat
* U_EXPORT2
create(EStyle timeStyle
, EStyle dateStyle
, const Locale
&);
595 * Field selector for FieldPosition for DateFormat fields.
596 * @obsolete ICU 3.4 use UDateFormatField instead, since this API will be
597 * removed in that release
601 // Obsolete; use UDateFormatField instead
602 kEraField
= UDAT_ERA_FIELD
,
603 kYearField
= UDAT_YEAR_FIELD
,
604 kMonthField
= UDAT_MONTH_FIELD
,
605 kDateField
= UDAT_DATE_FIELD
,
606 kHourOfDay1Field
= UDAT_HOUR_OF_DAY1_FIELD
,
607 kHourOfDay0Field
= UDAT_HOUR_OF_DAY0_FIELD
,
608 kMinuteField
= UDAT_MINUTE_FIELD
,
609 kSecondField
= UDAT_SECOND_FIELD
,
610 kMillisecondField
= UDAT_FRACTIONAL_SECOND_FIELD
,
611 kDayOfWeekField
= UDAT_DAY_OF_WEEK_FIELD
,
612 kDayOfYearField
= UDAT_DAY_OF_YEAR_FIELD
,
613 kDayOfWeekInMonthField
= UDAT_DAY_OF_WEEK_IN_MONTH_FIELD
,
614 kWeekOfYearField
= UDAT_WEEK_OF_YEAR_FIELD
,
615 kWeekOfMonthField
= UDAT_WEEK_OF_MONTH_FIELD
,
616 kAmPmField
= UDAT_AM_PM_FIELD
,
617 kHour1Field
= UDAT_HOUR1_FIELD
,
618 kHour0Field
= UDAT_HOUR0_FIELD
,
619 kTimezoneField
= UDAT_TIMEZONE_FIELD
,
620 kYearWOYField
= UDAT_YEAR_WOY_FIELD
,
621 kDOWLocalField
= UDAT_DOW_LOCAL_FIELD
,
622 kExtendedYearField
= UDAT_EXTENDED_YEAR_FIELD
,
623 kJulianDayField
= UDAT_JULIAN_DAY_FIELD
,
624 kMillisecondsInDayField
= UDAT_MILLISECONDS_IN_DAY_FIELD
,
626 // Obsolete; use UDateFormatField instead
627 ERA_FIELD
= UDAT_ERA_FIELD
,
628 YEAR_FIELD
= UDAT_YEAR_FIELD
,
629 MONTH_FIELD
= UDAT_MONTH_FIELD
,
630 DATE_FIELD
= UDAT_DATE_FIELD
,
631 HOUR_OF_DAY1_FIELD
= UDAT_HOUR_OF_DAY1_FIELD
,
632 HOUR_OF_DAY0_FIELD
= UDAT_HOUR_OF_DAY0_FIELD
,
633 MINUTE_FIELD
= UDAT_MINUTE_FIELD
,
634 SECOND_FIELD
= UDAT_SECOND_FIELD
,
635 MILLISECOND_FIELD
= UDAT_FRACTIONAL_SECOND_FIELD
,
636 DAY_OF_WEEK_FIELD
= UDAT_DAY_OF_WEEK_FIELD
,
637 DAY_OF_YEAR_FIELD
= UDAT_DAY_OF_YEAR_FIELD
,
638 DAY_OF_WEEK_IN_MONTH_FIELD
= UDAT_DAY_OF_WEEK_IN_MONTH_FIELD
,
639 WEEK_OF_YEAR_FIELD
= UDAT_WEEK_OF_YEAR_FIELD
,
640 WEEK_OF_MONTH_FIELD
= UDAT_WEEK_OF_MONTH_FIELD
,
641 AM_PM_FIELD
= UDAT_AM_PM_FIELD
,
642 HOUR1_FIELD
= UDAT_HOUR1_FIELD
,
643 HOUR0_FIELD
= UDAT_HOUR0_FIELD
,
644 TIMEZONE_FIELD
= UDAT_TIMEZONE_FIELD
648 inline UnicodeString
&
649 DateFormat::format(const Formattable
& obj
,
650 UnicodeString
& appendTo
,
651 UErrorCode
& status
) const {
652 return Format::format(obj
, appendTo
, status
);
656 #endif /* #if !UCONFIG_NO_FORMATTING */