2
********************************************************************************
3
* Copyright (C) 1997-2010, 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.
40
class DateTimePatternGenerator;
43
* DateFormat is an abstract class for a family of classes that convert dates and
44
* times from their internal representations to textual form and back again in a
45
* language-independent manner. Converting from the internal representation (milliseconds
46
* since midnight, January 1, 1970) to text is known as "formatting," and converting
47
* from text to millis is known as "parsing." We currently define only one concrete
48
* subclass of DateFormat: SimpleDateFormat, which can handle pretty much all normal
49
* date formatting and parsing actions.
51
* DateFormat helps you to format and parse dates for any locale. Your code can
52
* be completely independent of the locale conventions for months, days of the
53
* week, or even the calendar format: lunar vs. solar.
55
* To format a date for the current Locale, use one of the static factory
59
* DateFormat* dfmt = DateFormat::createDateInstance();
60
* UDate myDate = Calendar::getNow();
61
* UnicodeString myString;
62
* myString = dfmt->format( myDate, myString );
65
* If you are formatting multiple numbers, it is more efficient to get the
66
* format and use it multiple times so that the system doesn't have to fetch the
67
* information about the local language and country conventions multiple times.
70
* DateFormat* df = DateFormat::createDateInstance();
71
* UnicodeString myString;
72
* UDate myDateArr[] = { 0.0, 100000000.0, 2000000000.0 }; // test values
73
* for (int32_t i = 0; i < 3; ++i) {
75
* cout << df->format( myDateArr[i], myString ) << endl;
79
* To get specific fields of a date, you can use UFieldPosition to
80
* get specific fields.
83
* DateFormat* dfmt = DateFormat::createDateInstance();
84
* FieldPosition pos(DateFormat::YEAR_FIELD);
85
* UnicodeString myString;
86
* myString = dfmt->format( myDate, myString );
87
* cout << myString << endl;
88
* cout << pos.getBeginIndex() << "," << pos. getEndIndex() << endl;
91
* To format a date for a different Locale, specify it in the call to
92
* createDateInstance().
96
* DateFormat::createDateInstance( DateFormat::SHORT, Locale::getFrance());
99
* You can use a DateFormat to parse also.
102
* UErrorCode status = U_ZERO_ERROR;
103
* UDate myDate = df->parse(myString, status);
106
* Use createDateInstance() to produce the normal date format for that country.
107
* There are other static factory methods available. Use createTimeInstance()
108
* to produce the normal time format for that country. Use createDateTimeInstance()
109
* to produce a DateFormat that formats both date and time. You can pass in
110
* different options to these factory methods to control the length of the
111
* result; from SHORT to MEDIUM to LONG to FULL. The exact result depends on the
112
* locale, but generally:
114
* <li> SHORT is completely numeric, such as 12/13/52 or 3:30pm
115
* <li> MEDIUM is longer, such as Jan 12, 1952
116
* <li> LONG is longer, such as January 12, 1952 or 3:30:32pm
117
* <li> FULL is pretty completely specified, such as
118
* Tuesday, April 12, 1952 AD or 3:30:42pm PST.
120
* You can also set the time zone on the format if you wish. If you want even
121
* more control over the format or parsing, (or want to give your users more
122
* control), you can try casting the DateFormat you get from the factory methods
123
* to a SimpleDateFormat. This will work for the majority of countries; just
124
* remember to chck getDynamicClassID() before carrying out the cast.
126
* You can also use forms of the parse and format methods with ParsePosition and
127
* FieldPosition to allow you to
129
* <li> Progressively parse through pieces of a string.
130
* <li> Align any particular field, or find out where it is for selection
134
* <p><em>User subclasses are not supported.</em> While clients may write
135
* subclasses, such code will not necessarily work and will not be
136
* guaranteed to work stably from release to release.
138
class U_I18N_API DateFormat : public Format {
142
* Constants for various style patterns. These reflect the order of items in
143
* the DateTimePatterns resource. There are 4 time patterns, 4 date patterns,
144
* the default date-time pattern, and 4 date-time patterns. Each block of 4 values
145
* in the resource occurs in the order full, long, medium, short.
157
kDateOffset = kShort + 1,
158
// kFull + kDateOffset = 4
159
// kLong + kDateOffset = 5
160
// kMedium + kDateOffset = 6
161
// kShort + kDateOffset = 7
166
kDateTimeOffset = kDateTime + 1,
167
// kFull + kDateTimeOffset = 9
168
// kLong + kDateTimeOffset = 10
169
// kMedium + kDateTimeOffset = 11
170
// kShort + kDateTimeOffset = 12
173
kRelative = (1 << 7),
175
kFullRelative = (kFull | kRelative),
177
kLongRelative = kLong | kRelative,
179
kMediumRelative = kMedium | kRelative,
181
kShortRelative = kShort | kRelative,
189
* These constants are provided for backwards compatibility only.
190
* Please use the C++ style constants defined above.
197
DATE_OFFSET = kDateOffset,
199
DATE_TIME = kDateTime
206
virtual ~DateFormat();
209
* Equality operator. Returns true if the two formats have the same behavior.
212
virtual UBool operator==(const Format&) const;
215
using Format::format;
218
* Format an object to produce a string. This method handles Formattable
219
* objects with a UDate type. If a the Formattable object type is not a Date,
220
* then it returns a failing UErrorCode.
222
* @param obj The object to format. Must be a Date.
223
* @param appendTo Output parameter to receive result.
224
* Result is appended to existing contents.
225
* @param pos On input: an alignment field, if desired.
226
* On output: the offsets of the alignment field.
227
* @param status Output param filled with success/failure status.
228
* @return Reference to 'appendTo' parameter.
231
virtual UnicodeString& format(const Formattable& obj,
232
UnicodeString& appendTo,
234
UErrorCode& status) const;
237
* Format an object to produce a string. This method handles Formattable
238
* objects with a UDate type. If a the Formattable object type is not a Date,
239
* then it returns a failing UErrorCode.
241
* @param obj The object to format. Must be a Date.
242
* @param appendTo Output parameter to receive result.
243
* Result is appended to existing contents.
244
* @param posIter On return, can be used to iterate over positions
245
* of fields generated by this format call. Field values
246
* are defined in UDateFormatField. Can be NULL.
247
* @param status Output param filled with success/failure status.
248
* @return Reference to 'appendTo' parameter.
251
virtual UnicodeString& format(const Formattable& obj,
252
UnicodeString& appendTo,
253
FieldPositionIterator* posIter,
254
UErrorCode& status) const;
256
* Formats a date into a date/time string. This is an abstract method which
257
* concrete subclasses must implement.
259
* On input, the FieldPosition parameter may have its "field" member filled with
260
* an enum value specifying a field. On output, the FieldPosition will be filled
261
* in with the text offsets for that field.
262
* <P> For example, given a time text
263
* "1996.07.10 AD at 15:08:56 PDT", if the given fieldPosition.field is
264
* UDAT_YEAR_FIELD, the offsets fieldPosition.beginIndex and
265
* statfieldPositionus.getEndIndex will be set to 0 and 4, respectively.
267
* that if the same time field appears more than once in a pattern, the status will
268
* be set for the first occurence of that time field. For instance,
269
* formatting a UDate to the time string "1 PM PDT (Pacific Daylight Time)"
270
* using the pattern "h a z (zzzz)" and the alignment field
271
* DateFormat::TIMEZONE_FIELD, the offsets fieldPosition.beginIndex and
272
* fieldPosition.getEndIndex will be set to 5 and 8, respectively, for the first
273
* occurence of the timezone pattern character 'z'.
275
* @param cal Calendar set to the date and time to be formatted
276
* into a date/time string. When the calendar type is
277
* different from the internal calendar held by this
278
* DateFormat instance, the date and the time zone will
279
* be inherited from the input calendar, but other calendar
280
* field values will be calculated by the internal calendar.
281
* @param appendTo Output parameter to receive result.
282
* Result is appended to existing contents.
283
* @param fieldPosition On input: an alignment field, if desired (see examples above)
284
* On output: the offsets of the alignment field (see examples above)
285
* @return Reference to 'appendTo' parameter.
288
virtual UnicodeString& format( Calendar& cal,
289
UnicodeString& appendTo,
290
FieldPosition& fieldPosition) const = 0;
293
* Formats a date into a date/time string. Subclasses should implement this method.
295
* @param cal Calendar set to the date and time to be formatted
296
* into a date/time string. When the calendar type is
297
* different from the internal calendar held by this
298
* DateFormat instance, the date and the time zone will
299
* be inherited from the input calendar, but other calendar
300
* field values will be calculated by the internal calendar.
301
* @param appendTo Output parameter to receive result.
302
* Result is appended to existing contents.
303
* @param posIter On return, can be used to iterate over positions
304
* of fields generated by this format call. Field values
305
* are defined in UDateFormatField. Can be NULL.
306
* @param status error status.
307
* @return Reference to 'appendTo' parameter.
310
virtual UnicodeString& format(Calendar& cal,
311
UnicodeString& appendTo,
312
FieldPositionIterator* posIter,
313
UErrorCode& status) const;
315
* Formats a UDate into a date/time string.
317
* On input, the FieldPosition parameter may have its "field" member filled with
318
* an enum value specifying a field. On output, the FieldPosition will be filled
319
* in with the text offsets for that field.
320
* <P> For example, given a time text
321
* "1996.07.10 AD at 15:08:56 PDT", if the given fieldPosition.field is
322
* UDAT_YEAR_FIELD, the offsets fieldPosition.beginIndex and
323
* statfieldPositionus.getEndIndex will be set to 0 and 4, respectively.
325
* that if the same time field appears more than once in a pattern, the status will
326
* be set for the first occurence of that time field. For instance,
327
* formatting a UDate to the time string "1 PM PDT (Pacific Daylight Time)"
328
* using the pattern "h a z (zzzz)" and the alignment field
329
* DateFormat::TIMEZONE_FIELD, the offsets fieldPosition.beginIndex and
330
* fieldPosition.getEndIndex will be set to 5 and 8, respectively, for the first
331
* occurence of the timezone pattern character 'z'.
333
* @param date UDate to be formatted into a date/time string.
334
* @param appendTo Output parameter to receive result.
335
* Result is appended to existing contents.
336
* @param fieldPosition On input: an alignment field, if desired (see examples above)
337
* On output: the offsets of the alignment field (see examples above)
338
* @return Reference to 'appendTo' parameter.
341
UnicodeString& format( UDate date,
342
UnicodeString& appendTo,
343
FieldPosition& fieldPosition) const;
346
* Formats a UDate into a date/time string.
348
* @param date UDate to be formatted into a date/time string.
349
* @param appendTo Output parameter to receive result.
350
* Result is appended to existing contents.
351
* @param posIter On return, can be used to iterate over positions
352
* of fields generated by this format call. Field values
353
* are defined in UDateFormatField. Can be NULL.
354
* @param status error status.
355
* @return Reference to 'appendTo' parameter.
358
UnicodeString& format(UDate date,
359
UnicodeString& appendTo,
360
FieldPositionIterator* posIter,
361
UErrorCode& status) const;
363
* Formats a UDate into a date/time string. If there is a problem, you won't
364
* know, using this method. Use the overloaded format() method which takes a
365
* FieldPosition& to detect formatting problems.
367
* @param date The UDate value to be formatted into a string.
368
* @param appendTo Output parameter to receive result.
369
* Result is appended to existing contents.
370
* @return Reference to 'appendTo' parameter.
373
UnicodeString& format(UDate date, UnicodeString& appendTo) const;
376
* Redeclared Format method.
378
* @param obj The object to be formatted into a string.
379
* @param appendTo Output parameter to receive result.
380
* Result is appended to existing contents.
381
* @param status Output param filled with success/failure status.
382
* @return Reference to 'appendTo' parameter.
385
UnicodeString& format(const Formattable& obj,
386
UnicodeString& appendTo,
387
UErrorCode& status) const;
390
* Parse a date/time string.
392
* @param text The string to be parsed into a UDate value.
393
* @param status Output param to be set to success/failure code. If
394
* 'text' cannot be parsed, it will be set to a failure
396
* @result The parsed UDate value, if successful.
399
virtual UDate parse( const UnicodeString& text,
400
UErrorCode& status) const;
403
* Parse a date/time string beginning at the given parse position. For
404
* example, a time text "07/10/96 4:5 PM, PDT" will be parsed into a Date
405
* that is equivalent to Date(837039928046).
407
* By default, parsing is lenient: If the input is not in the form used by
408
* this object's format method but can still be parsed as a date, then the
409
* parse succeeds. Clients may insist on strict adherence to the format by
410
* calling setLenient(false).
412
* @see DateFormat::setLenient(boolean)
414
* @param text The date/time string to be parsed
415
* @param cal a Calendar set to the date and time to be formatted
416
* into a date/time string. When the calendar type
417
* is different from the internal calendar held by this
418
* DateFormat instance, calendar field values will be
419
* parsed based on the internal calendar, then the result
420
* (time in milliseconds and time zone) will be set in
422
* @param pos On input, the position at which to start parsing; on
423
* output, the position at which parsing terminated, or the
424
* start position if the parse failed.
425
* @return A valid UDate if the input could be parsed.
428
virtual void parse( const UnicodeString& text,
430
ParsePosition& pos) const = 0;
433
* Parse a date/time string beginning at the given parse position. For
434
* example, a time text "07/10/96 4:5 PM, PDT" will be parsed into a Date
435
* that is equivalent to Date(837039928046).
437
* By default, parsing is lenient: If the input is not in the form used by
438
* this object's format method but can still be parsed as a date, then the
439
* parse succeeds. Clients may insist on strict adherence to the format by
440
* calling setLenient(false).
442
* @see DateFormat::setLenient(boolean)
444
* @param text The date/time string to be parsed
445
* @param pos On input, the position at which to start parsing; on
446
* output, the position at which parsing terminated, or the
447
* start position if the parse failed.
448
* @return A valid UDate if the input could be parsed.
451
UDate parse( const UnicodeString& text,
452
ParsePosition& pos) const;
455
* Parse a string to produce an object. This methods handles parsing of
456
* date/time strings into Formattable objects with UDate types.
458
* Before calling, set parse_pos.index to the offset you want to start
459
* parsing at in the source. After calling, parse_pos.index is the end of
460
* the text you parsed. If error occurs, index is unchanged.
462
* When parsing, leading whitespace is discarded (with a successful parse),
463
* while trailing whitespace is left as is.
465
* See Format::parseObject() for more.
467
* @param source The string to be parsed into an object.
468
* @param result Formattable to be set to the parse result.
469
* If parse fails, return contents are undefined.
470
* @param parse_pos The position to start parsing at. Upon return
471
* this param is set to the position after the
472
* last character successfully parsed. If the
473
* source is not parsed successfully, this param
474
* will remain unchanged.
475
* @return A newly created Formattable* object, or NULL
476
* on failure. The caller owns this and should
477
* delete it when done.
480
virtual void parseObject(const UnicodeString& source,
482
ParsePosition& parse_pos) const;
485
* Create a default date/time formatter that uses the SHORT style for both
486
* the date and the time.
488
* @return A date/time formatter which the caller owns.
491
static DateFormat* U_EXPORT2 createInstance(void);
494
* Creates a time formatter with the given formatting style for the given
497
* @param style The given formatting style. For example,
498
* SHORT for "h:mm a" in the US locale. Relative
499
* time styles are not currently supported.
500
* @param aLocale The given locale.
501
* @return A time formatter which the caller owns.
504
static DateFormat* U_EXPORT2 createTimeInstance(EStyle style = kDefault,
505
const Locale& aLocale = Locale::getDefault());
508
* Creates a date formatter with the given formatting style for the given
511
* @param style The given formatting style. For example,
512
* SHORT for "M/d/yy" in the US locale.
513
* @param aLocale The given locale.
514
* @return A date formatter which the caller owns.
517
static DateFormat* U_EXPORT2 createDateInstance(EStyle style = kDefault,
518
const Locale& aLocale = Locale::getDefault());
521
* Creates a date/time formatter with the given formatting styles for the
524
* @param dateStyle The given formatting style for the date portion of the result.
525
* For example, SHORT for "M/d/yy" in the US locale.
526
* @param timeStyle The given formatting style for the time portion of the result.
527
* For example, SHORT for "h:mm a" in the US locale. Relative
528
* time styles are not currently supported.
529
* @param aLocale The given locale.
530
* @return A date/time formatter which the caller owns.
533
static DateFormat* U_EXPORT2 createDateTimeInstance(EStyle dateStyle = kDefault,
534
EStyle timeStyle = kDefault,
535
const Locale& aLocale = Locale::getDefault());
538
* Gets the set of locales for which DateFormats are installed.
539
* @param count Filled in with the number of locales in the list that is returned.
540
* @return the set of locales for which DateFormats are installed. The caller
541
* does NOT own this list and must not delete it.
544
static const Locale* U_EXPORT2 getAvailableLocales(int32_t& count);
547
* Returns true if the formatter is set for lenient parsing.
550
virtual UBool isLenient(void) const;
553
* Specify whether or not date/time parsing is to be lenient. With lenient
554
* parsing, the parser may use heuristics to interpret inputs that do not
555
* precisely match this object's format. With strict parsing, inputs must
556
* match this object's format.
558
* @param lenient True specifies date/time interpretation to be lenient.
559
* @see Calendar::setLenient
562
virtual void setLenient(UBool lenient);
565
* Gets the calendar associated with this date/time formatter.
566
* @return the calendar associated with this date/time formatter.
569
virtual const Calendar* getCalendar(void) const;
572
* Set the calendar to be used by this date format. Initially, the default
573
* calendar for the specified or default locale is used. The caller should
574
* not delete the Calendar object after it is adopted by this call.
575
* Adopting a new calendar will change to the default symbols.
577
* @param calendarToAdopt Calendar object to be adopted.
580
virtual void adoptCalendar(Calendar* calendarToAdopt);
583
* Set the calendar to be used by this date format. Initially, the default
584
* calendar for the specified or default locale is used.
586
* @param newCalendar Calendar object to be set.
589
virtual void setCalendar(const Calendar& newCalendar);
593
* Gets the number formatter which this date/time formatter uses to format
594
* and parse the numeric portions of the pattern.
595
* @return the number formatter which this date/time formatter uses.
598
virtual const NumberFormat* getNumberFormat(void) const;
601
* Allows you to set the number formatter. The caller should
602
* not delete the NumberFormat object after it is adopted by this call.
603
* @param formatToAdopt NumberFormat object to be adopted.
606
virtual void adoptNumberFormat(NumberFormat* formatToAdopt);
609
* Allows you to set the number formatter.
610
* @param newNumberFormat NumberFormat object to be set.
613
virtual void setNumberFormat(const NumberFormat& newNumberFormat);
616
* Returns a reference to the TimeZone used by this DateFormat's calendar.
617
* @return the time zone associated with the calendar of DateFormat.
620
virtual const TimeZone& getTimeZone(void) const;
623
* Sets the time zone for the calendar of this DateFormat object. The caller
624
* no longer owns the TimeZone object and should not delete it after this call.
625
* @param zoneToAdopt the TimeZone to be adopted.
628
virtual void adoptTimeZone(TimeZone* zoneToAdopt);
631
* Sets the time zone for the calendar of this DateFormat object.
632
* @param zone the new time zone.
635
virtual void setTimeZone(const TimeZone& zone);
639
* Default constructor. Creates a DateFormat with no Calendar or NumberFormat
640
* associated with it. This constructor depends on the subclasses to fill in
641
* the calendar and numberFormat fields.
650
DateFormat(const DateFormat&);
653
* Default assignment operator.
656
DateFormat& operator=(const DateFormat&);
659
* The calendar that DateFormat uses to produce the time field values needed
660
* to implement date/time formatting. Subclasses should generally initialize
661
* this to the default calendar for the locale associated with this DateFormat.
667
* The number formatter that DateFormat uses to format numbers in dates and
668
* times. Subclasses should generally initialize this to the default number
669
* format for the locale associated with this DateFormat.
672
NumberFormat* fNumberFormat;
676
* Gets the date/time formatter with the given formatting styles for the
678
* @param dateStyle the given date formatting style.
679
* @param timeStyle the given time formatting style.
680
* @param inLocale the given locale.
681
* @return a date/time formatter, or 0 on failure.
683
static DateFormat* U_EXPORT2 create(EStyle timeStyle, EStyle dateStyle, const Locale&);
687
* Field selector for FieldPosition for DateFormat fields.
688
* @obsolete ICU 3.4 use UDateFormatField instead, since this API will be
689
* removed in that release
693
// Obsolete; use UDateFormatField instead
694
kEraField = UDAT_ERA_FIELD,
695
kYearField = UDAT_YEAR_FIELD,
696
kMonthField = UDAT_MONTH_FIELD,
697
kDateField = UDAT_DATE_FIELD,
698
kHourOfDay1Field = UDAT_HOUR_OF_DAY1_FIELD,
699
kHourOfDay0Field = UDAT_HOUR_OF_DAY0_FIELD,
700
kMinuteField = UDAT_MINUTE_FIELD,
701
kSecondField = UDAT_SECOND_FIELD,
702
kMillisecondField = UDAT_FRACTIONAL_SECOND_FIELD,
703
kDayOfWeekField = UDAT_DAY_OF_WEEK_FIELD,
704
kDayOfYearField = UDAT_DAY_OF_YEAR_FIELD,
705
kDayOfWeekInMonthField = UDAT_DAY_OF_WEEK_IN_MONTH_FIELD,
706
kWeekOfYearField = UDAT_WEEK_OF_YEAR_FIELD,
707
kWeekOfMonthField = UDAT_WEEK_OF_MONTH_FIELD,
708
kAmPmField = UDAT_AM_PM_FIELD,
709
kHour1Field = UDAT_HOUR1_FIELD,
710
kHour0Field = UDAT_HOUR0_FIELD,
711
kTimezoneField = UDAT_TIMEZONE_FIELD,
712
kYearWOYField = UDAT_YEAR_WOY_FIELD,
713
kDOWLocalField = UDAT_DOW_LOCAL_FIELD,
714
kExtendedYearField = UDAT_EXTENDED_YEAR_FIELD,
715
kJulianDayField = UDAT_JULIAN_DAY_FIELD,
716
kMillisecondsInDayField = UDAT_MILLISECONDS_IN_DAY_FIELD,
718
// Obsolete; use UDateFormatField instead
719
ERA_FIELD = UDAT_ERA_FIELD,
720
YEAR_FIELD = UDAT_YEAR_FIELD,
721
MONTH_FIELD = UDAT_MONTH_FIELD,
722
DATE_FIELD = UDAT_DATE_FIELD,
723
HOUR_OF_DAY1_FIELD = UDAT_HOUR_OF_DAY1_FIELD,
724
HOUR_OF_DAY0_FIELD = UDAT_HOUR_OF_DAY0_FIELD,
725
MINUTE_FIELD = UDAT_MINUTE_FIELD,
726
SECOND_FIELD = UDAT_SECOND_FIELD,
727
MILLISECOND_FIELD = UDAT_FRACTIONAL_SECOND_FIELD,
728
DAY_OF_WEEK_FIELD = UDAT_DAY_OF_WEEK_FIELD,
729
DAY_OF_YEAR_FIELD = UDAT_DAY_OF_YEAR_FIELD,
730
DAY_OF_WEEK_IN_MONTH_FIELD = UDAT_DAY_OF_WEEK_IN_MONTH_FIELD,
731
WEEK_OF_YEAR_FIELD = UDAT_WEEK_OF_YEAR_FIELD,
732
WEEK_OF_MONTH_FIELD = UDAT_WEEK_OF_MONTH_FIELD,
733
AM_PM_FIELD = UDAT_AM_PM_FIELD,
734
HOUR1_FIELD = UDAT_HOUR1_FIELD,
735
HOUR0_FIELD = UDAT_HOUR0_FIELD,
736
TIMEZONE_FIELD = UDAT_TIMEZONE_FIELD
740
inline UnicodeString&
741
DateFormat::format(const Formattable& obj,
742
UnicodeString& appendTo,
743
UErrorCode& status) const {
744
return Format::format(obj, appendTo, status);
748
#endif /* #if !UCONFIG_NO_FORMATTING */