dtitvfmt.h (50689B)
1 // © 2016 and later: Unicode, Inc. and others. 2 // License & terms of use: http://www.unicode.org/copyright.html 3 /******************************************************************************** 4 * Copyright (C) 2008-2016, International Business Machines Corporation and 5 * others. All Rights Reserved. 6 ******************************************************************************* 7 * 8 * File DTITVFMT.H 9 * 10 ******************************************************************************* 11 */ 12 13 #ifndef __DTITVFMT_H__ 14 #define __DTITVFMT_H__ 15 16 17 #include "unicode/utypes.h" 18 19 #if U_SHOW_CPLUSPLUS_API 20 21 /** 22 * \file 23 * \brief C++ API: Format and parse date interval in a language-independent manner. 24 */ 25 26 #if !UCONFIG_NO_FORMATTING 27 28 #include "unicode/ucal.h" 29 #include "unicode/smpdtfmt.h" 30 #include "unicode/dtintrv.h" 31 #include "unicode/dtitvinf.h" 32 #include "unicode/dtptngen.h" 33 #include "unicode/formattedvalue.h" 34 #include "unicode/udisplaycontext.h" 35 36 U_NAMESPACE_BEGIN 37 38 39 class FormattedDateIntervalData; 40 class DateIntervalFormat; 41 42 /** 43 * An immutable class containing the result of a date interval formatting operation. 44 * 45 * Instances of this class are immutable and thread-safe. 46 * 47 * When calling nextPosition(): 48 * The fields are returned from left to right. The special field category 49 * UFIELD_CATEGORY_DATE_INTERVAL_SPAN is used to indicate which datetime 50 * primitives came from which arguments: 0 means fromCalendar, and 1 means 51 * toCalendar. The span category will always occur before the 52 * corresponding fields in UFIELD_CATEGORY_DATE 53 * in the nextPosition() iterator. 54 * 55 * Not intended for public subclassing. 56 * 57 * @stable ICU 64 58 */ 59 class U_I18N_API FormattedDateInterval : public UMemory, public FormattedValue { 60 public: 61 /** 62 * Default constructor; makes an empty FormattedDateInterval. 63 * @stable ICU 64 64 */ 65 FormattedDateInterval() : fData(nullptr), fErrorCode(U_INVALID_STATE_ERROR) {} 66 67 /** 68 * Move constructor: Leaves the source FormattedDateInterval in an undefined state. 69 * @stable ICU 64 70 */ 71 FormattedDateInterval(FormattedDateInterval&& src) noexcept; 72 73 /** 74 * Destruct an instance of FormattedDateInterval. 75 * @stable ICU 64 76 */ 77 virtual ~FormattedDateInterval() override; 78 79 /** Copying not supported; use move constructor instead. */ 80 FormattedDateInterval(const FormattedDateInterval&) = delete; 81 82 /** Copying not supported; use move assignment instead. */ 83 FormattedDateInterval& operator=(const FormattedDateInterval&) = delete; 84 85 /** 86 * Move assignment: Leaves the source FormattedDateInterval in an undefined state. 87 * @stable ICU 64 88 */ 89 FormattedDateInterval& operator=(FormattedDateInterval&& src) noexcept; 90 91 /** @copydoc FormattedValue::toString() */ 92 UnicodeString toString(UErrorCode& status) const override; 93 94 /** @copydoc FormattedValue::toTempString() */ 95 UnicodeString toTempString(UErrorCode& status) const override; 96 97 /** @copydoc FormattedValue::appendTo() */ 98 Appendable &appendTo(Appendable& appendable, UErrorCode& status) const override; 99 100 /** @copydoc FormattedValue::nextPosition() */ 101 UBool nextPosition(ConstrainedFieldPosition& cfpos, UErrorCode& status) const override; 102 103 private: 104 FormattedDateIntervalData *fData; 105 UErrorCode fErrorCode; 106 explicit FormattedDateInterval(FormattedDateIntervalData *results) 107 : fData(results), fErrorCode(U_ZERO_ERROR) {} 108 explicit FormattedDateInterval(UErrorCode errorCode) 109 : fData(nullptr), fErrorCode(errorCode) {} 110 friend class DateIntervalFormat; 111 }; 112 113 114 /** 115 * DateIntervalFormat is a class for formatting and parsing date 116 * intervals in a language-independent manner. 117 * Only formatting is supported, parsing is not supported. 118 * 119 * <P> 120 * Date interval means from one date to another date, 121 * for example, from "Jan 11, 2008" to "Jan 18, 2008". 122 * We introduced class DateInterval to represent it. 123 * DateInterval is a pair of UDate, which is 124 * the standard milliseconds since 24:00 GMT, Jan 1, 1970. 125 * 126 * <P> 127 * DateIntervalFormat formats a DateInterval into 128 * text as compactly as possible. 129 * For example, the date interval format from "Jan 11, 2008" to "Jan 18,. 2008" 130 * is "Jan 11-18, 2008" for English. 131 * And it parses text into DateInterval, 132 * although initially, parsing is not supported. 133 * 134 * <P> 135 * There is no structural information in date time patterns. 136 * For any punctuations and string literals inside a date time pattern, 137 * we do not know whether it is just a separator, or a prefix, or a suffix. 138 * Without such information, so, it is difficult to generate a sub-pattern 139 * (or super-pattern) by algorithm. 140 * So, formatting a DateInterval is pattern-driven. It is very 141 * similar to formatting in SimpleDateFormat. 142 * We introduce class DateIntervalInfo to save date interval 143 * patterns, similar to date time pattern in SimpleDateFormat. 144 * 145 * <P> 146 * Logically, the interval patterns are mappings 147 * from (skeleton, the_largest_different_calendar_field) 148 * to (date_interval_pattern). 149 * 150 * <P> 151 * A skeleton 152 * <ol> 153 * <li> 154 * only keeps the field pattern letter and ignores all other parts 155 * in a pattern, such as space, punctuations, and string literals. 156 * </li> 157 * <li> 158 * hides the order of fields. 159 * </li> 160 * <li> 161 * might hide a field's pattern letter length. 162 * </li> 163 * </ol> 164 * 165 * For those non-digit calendar fields, the pattern letter length is 166 * important, such as MMM, MMMM, and MMMMM; EEE and EEEE, 167 * and the field's pattern letter length is honored. 168 * 169 * For the digit calendar fields, such as M or MM, d or dd, yy or yyyy, 170 * the field pattern length is ignored and the best match, which is defined 171 * in date time patterns, will be returned without honor the field pattern 172 * letter length in skeleton. 173 * 174 * <P> 175 * The calendar fields we support for interval formatting are: 176 * year, month, date, day-of-week, am-pm, hour, hour-of-day, minute, second, 177 * and millisecond. 178 * (though we do not currently have specific intervalFormat date for skeletons 179 * with seconds and millisecond). 180 * Those calendar fields can be defined in the following order: 181 * year > month > date > hour (in day) > minute > second > millisecond 182 * 183 * The largest different calendar fields between 2 calendars is the 184 * first different calendar field in above order. 185 * 186 * For example: the largest different calendar fields between "Jan 10, 2007" 187 * and "Feb 20, 2008" is year. 188 * 189 * <P> 190 * For other calendar fields, the compact interval formatting is not 191 * supported. And the interval format will be fall back to fall-back 192 * patterns, which is mostly "{date0} - {date1}". 193 * 194 * <P> 195 * There is a set of pre-defined static skeleton strings. 196 * There are pre-defined interval patterns for those pre-defined skeletons 197 * in locales' resource files. 198 * For example, for a skeleton UDAT_YEAR_ABBR_MONTH_DAY, which is "yMMMd", 199 * in en_US, if the largest different calendar field between date1 and date2 200 * is "year", the date interval pattern is "MMM d, yyyy - MMM d, yyyy", 201 * such as "Jan 10, 2007 - Jan 10, 2008". 202 * If the largest different calendar field between date1 and date2 is "month", 203 * the date interval pattern is "MMM d - MMM d, yyyy", 204 * such as "Jan 10 - Feb 10, 2007". 205 * If the largest different calendar field between date1 and date2 is "day", 206 * the date interval pattern is "MMM d-d, yyyy", such as "Jan 10-20, 2007". 207 * 208 * For date skeleton, the interval patterns when year, or month, or date is 209 * different are defined in resource files. 210 * For time skeleton, the interval patterns when am/pm, or hour, or minute is 211 * different are defined in resource files. 212 * 213 * <P> 214 * If a skeleton is not found in a locale's DateIntervalInfo, which means 215 * the interval patterns for the skeleton is not defined in resource file, 216 * the interval pattern will falls back to the interval "fallback" pattern 217 * defined in resource file. 218 * If the interval "fallback" pattern is not defined, the default fall-back 219 * is "{date0} - {data1}". 220 * 221 * <P> 222 * For the combination of date and time, 223 * The rule to generate interval patterns are: 224 * <ol> 225 * <li> 226 * when the year, month, or day differs, falls back to fall-back 227 * interval pattern, which mostly is the concatenate the two original 228 * expressions with a separator between, 229 * For example, interval pattern from "Jan 10, 2007 10:10 am" 230 * to "Jan 11, 2007 10:10am" is 231 * "Jan 10, 2007 10:10 am - Jan 11, 2007 10:10am" 232 * </li> 233 * <li> 234 * otherwise, present the date followed by the range expression 235 * for the time. 236 * For example, interval pattern from "Jan 10, 2007 10:10 am" 237 * to "Jan 10, 2007 11:10am" is "Jan 10, 2007 10:10 am - 11:10am" 238 * </li> 239 * </ol> 240 * 241 * 242 * <P> 243 * If two dates are the same, the interval pattern is the single date pattern. 244 * For example, interval pattern from "Jan 10, 2007" to "Jan 10, 2007" is 245 * "Jan 10, 2007". 246 * 247 * Or if the presenting fields between 2 dates have the exact same values, 248 * the interval pattern is the single date pattern. 249 * For example, if user only requests year and month, 250 * the interval pattern from "Jan 10, 2007" to "Jan 20, 2007" is "Jan 2007". 251 * 252 * <P> 253 * DateIntervalFormat needs the following information for correct 254 * formatting: time zone, calendar type, pattern, date format symbols, 255 * and date interval patterns. 256 * It can be instantiated in 2 ways: 257 * <ol> 258 * <li> 259 * create an instance using default or given locale plus given skeleton. 260 * Users are encouraged to created date interval formatter this way and 261 * to use the pre-defined skeleton macros, such as 262 * UDAT_YEAR_NUM_MONTH, which consists the calendar fields and 263 * the format style. 264 * </li> 265 * <li> 266 * create an instance using default or given locale plus given skeleton 267 * plus a given DateIntervalInfo. 268 * This factory method is for powerful users who want to provide their own 269 * interval patterns. 270 * Locale provides the timezone, calendar, and format symbols information. 271 * Local plus skeleton provides full pattern information. 272 * DateIntervalInfo provides the date interval patterns. 273 * </li> 274 * </ol> 275 * 276 * <P> 277 * For the calendar field pattern letter, such as G, y, M, d, a, h, H, m, s etc. 278 * DateIntervalFormat uses the same syntax as that of 279 * DateTime format. 280 * 281 * <P> 282 * Code Sample: general usage 283 * <pre> 284 * \code 285 * // the date interval object which the DateIntervalFormat formats on 286 * // and parses into 287 * DateInterval* dtInterval = new DateInterval(1000*3600*24, 1000*3600*24*2); 288 * UErrorCode status = U_ZERO_ERROR; 289 * DateIntervalFormat* dtIntervalFmt = DateIntervalFormat::createInstance( 290 * UDAT_YEAR_MONTH_DAY, 291 * Locale("en", "GB", ""), status); 292 * UnicodeUnicodeString dateIntervalString; 293 * FieldPosition pos = 0; 294 * // formatting 295 * dtIntervalFmt->format(dtInterval, dateIntervalUnicodeString, pos, status); 296 * delete dtIntervalFmt; 297 * \endcode 298 * </pre> 299 */ 300 class U_I18N_API_CLASS DateIntervalFormat : public Format { 301 public: 302 303 /** 304 * Construct a DateIntervalFormat from skeleton and the default locale. 305 * 306 * This is a convenient override of 307 * createInstance(const UnicodeString& skeleton, const Locale& locale, 308 * UErrorCode&) 309 * with the value of locale as default locale. 310 * 311 * @param skeleton the skeleton on which interval format based. 312 * @param status output param set to success/failure code on exit 313 * @return a date time interval formatter which the caller owns. 314 * @stable ICU 4.0 315 */ 316 U_I18N_API static DateIntervalFormat* createInstance(const UnicodeString& skeleton, 317 UErrorCode& status); 318 319 /** 320 * Construct a DateIntervalFormat from skeleton and a given locale. 321 * <P> 322 * In this factory method, 323 * the date interval pattern information is load from resource files. 324 * Users are encouraged to created date interval formatter this way and 325 * to use the pre-defined skeleton macros. 326 * 327 * <P> 328 * There are pre-defined skeletons (defined in udate.h) having predefined 329 * interval patterns in resource files. 330 * Users are encouraged to use those macros. 331 * For example: 332 * DateIntervalFormat::createInstance(UDAT_MONTH_DAY, status) 333 * 334 * The given Locale provides the interval patterns. 335 * For example, for en_GB, if skeleton is UDAT_YEAR_ABBR_MONTH_WEEKDAY_DAY, 336 * which is "yMMMEEEd", 337 * the interval patterns defined in resource file to above skeleton are: 338 * "EEE, d MMM, yyyy - EEE, d MMM, yyyy" for year differs, 339 * "EEE, d MMM - EEE, d MMM, yyyy" for month differs, 340 * "EEE, d - EEE, d MMM, yyyy" for day differs, 341 * @param skeleton the skeleton on which the interval format is based. 342 * @param locale the given locale 343 * @param status output param set to success/failure code on exit 344 * @return a date time interval formatter which the caller owns. 345 * @stable ICU 4.0 346 */ 347 348 U_I18N_API static DateIntervalFormat* createInstance(const UnicodeString& skeleton, 349 const Locale& locale, 350 UErrorCode& status); 351 352 /** 353 * Construct a DateIntervalFormat from skeleton 354 * DateIntervalInfo, and default locale. 355 * 356 * This is a convenient override of 357 * createInstance(const UnicodeString& skeleton, const Locale& locale, 358 * const DateIntervalInfo& dtitvinf, UErrorCode&) 359 * with the locale value as default locale. 360 * 361 * @param skeleton the skeleton on which interval format based. 362 * @param dtitvinf the DateIntervalInfo object. 363 * @param status output param set to success/failure code on exit 364 * @return a date time interval formatter which the caller owns. 365 * @stable ICU 4.0 366 */ 367 U_I18N_API static DateIntervalFormat* createInstance(const UnicodeString& skeleton, 368 const DateIntervalInfo& dtitvinf, 369 UErrorCode& status); 370 371 /** 372 * Construct a DateIntervalFormat from skeleton 373 * a DateIntervalInfo, and the given locale. 374 * 375 * <P> 376 * In this factory method, user provides its own date interval pattern 377 * information, instead of using those pre-defined data in resource file. 378 * This factory method is for powerful users who want to provide their own 379 * interval patterns. 380 * <P> 381 * There are pre-defined skeletons (defined in udate.h) having predefined 382 * interval patterns in resource files. 383 * Users are encouraged to use those macros. 384 * For example: 385 * DateIntervalFormat::createInstance(UDAT_MONTH_DAY, status) 386 * 387 * The DateIntervalInfo provides the interval patterns. 388 * and the DateIntervalInfo ownership remains to the caller. 389 * 390 * User are encouraged to set default interval pattern in DateIntervalInfo 391 * as well, if they want to set other interval patterns ( instead of 392 * reading the interval patterns from resource files). 393 * When the corresponding interval pattern for a largest calendar different 394 * field is not found ( if user not set it ), interval format fallback to 395 * the default interval pattern. 396 * If user does not provide default interval pattern, it fallback to 397 * "{date0} - {date1}" 398 * 399 * @param skeleton the skeleton on which interval format based. 400 * @param locale the given locale 401 * @param dtitvinf the DateIntervalInfo object. 402 * @param status output param set to success/failure code on exit 403 * @return a date time interval formatter which the caller owns. 404 * @stable ICU 4.0 405 */ 406 U_I18N_API static DateIntervalFormat* createInstance(const UnicodeString& skeleton, 407 const Locale& locale, 408 const DateIntervalInfo& dtitvinf, 409 UErrorCode& status); 410 411 /** 412 * Destructor. 413 * @stable ICU 4.0 414 */ 415 U_I18N_API virtual ~DateIntervalFormat(); 416 417 /** 418 * Clone this Format object polymorphically. The caller owns the result and 419 * should delete it when done. 420 * @return A copy of the object. 421 * @stable ICU 4.0 422 */ 423 U_I18N_API virtual DateIntervalFormat* clone() const override; 424 425 /** 426 * Return true if the given Format objects are semantically equal. Objects 427 * of different subclasses are considered unequal. 428 * @param other the object to be compared with. 429 * @return true if the given Format objects are semantically equal. 430 * @stable ICU 4.0 431 */ 432 U_I18N_API virtual bool operator==(const Format& other) const override; 433 434 /** 435 * Return true if the given Format objects are not semantically equal. 436 * Objects of different subclasses are considered unequal. 437 * @param other the object to be compared with. 438 * @return true if the given Format objects are not semantically equal. 439 * @stable ICU 4.0 440 */ 441 U_I18N_API bool operator!=(const Format& other) const; 442 443 using Format::format; 444 445 /** 446 * Format an object to produce a string. This method handles Formattable 447 * objects with a DateInterval type. 448 * If a the Formattable object type is not a DateInterval, 449 * then it returns a failing UErrorCode. 450 * 451 * @param obj The object to format. 452 * Must be a DateInterval. 453 * @param appendTo Output parameter to receive result. 454 * Result is appended to existing contents. 455 * @param fieldPosition On input: an alignment field, if desired. 456 * On output: the offsets of the alignment field. 457 * There may be multiple instances of a given field type 458 * in an interval format; in this case the fieldPosition 459 * offsets refer to the first instance. 460 * @param status Output param filled with success/failure status. 461 * @return Reference to 'appendTo' parameter. 462 * @stable ICU 4.0 463 */ 464 U_I18N_API virtual UnicodeString& format(const Formattable& obj, 465 UnicodeString& appendTo, 466 FieldPosition& fieldPosition, 467 UErrorCode& status) const override; 468 469 /** 470 * Format a DateInterval to produce a string. 471 * 472 * @param dtInterval DateInterval to be formatted. 473 * @param appendTo Output parameter to receive result. 474 * Result is appended to existing contents. 475 * @param fieldPosition On input: an alignment field, if desired. 476 * On output: the offsets of the alignment field. 477 * There may be multiple instances of a given field type 478 * in an interval format; in this case the fieldPosition 479 * offsets refer to the first instance. 480 * @param status Output param filled with success/failure status. 481 * @return Reference to 'appendTo' parameter. 482 * @stable ICU 4.0 483 */ 484 U_I18N_API UnicodeString& format(const DateInterval* dtInterval, 485 UnicodeString& appendTo, 486 FieldPosition& fieldPosition, 487 UErrorCode& status) const; 488 489 /** 490 * Format a DateInterval to produce a FormattedDateInterval. 491 * 492 * The FormattedDateInterval exposes field information about the formatted string. 493 * 494 * @param dtInterval DateInterval to be formatted. 495 * @param status Set if an error occurs. 496 * @return A FormattedDateInterval containing the format result. 497 * @stable ICU 64 498 */ 499 U_I18N_API FormattedDateInterval formatToValue(const DateInterval& dtInterval, 500 UErrorCode& status) const; 501 502 /** 503 * Format 2 Calendars to produce a string. 504 * 505 * Note: "fromCalendar" and "toCalendar" are not const, 506 * since calendar is not const in SimpleDateFormat::format(Calendar&), 507 * 508 * @param fromCalendar calendar set to the from date in date interval 509 * to be formatted into date interval string 510 * @param toCalendar calendar set to the to date in date interval 511 * to be formatted into date interval string 512 * @param appendTo Output parameter to receive result. 513 * Result is appended to existing contents. 514 * @param fieldPosition On input: an alignment field, if desired. 515 * On output: the offsets of the alignment field. 516 * There may be multiple instances of a given field type 517 * in an interval format; in this case the fieldPosition 518 * offsets refer to the first instance. 519 * @param status Output param filled with success/failure status. 520 * Caller needs to make sure it is SUCCESS 521 * at the function entrance 522 * @return Reference to 'appendTo' parameter. 523 * @stable ICU 4.0 524 */ 525 U_I18N_API UnicodeString& format(Calendar& fromCalendar, 526 Calendar& toCalendar, 527 UnicodeString& appendTo, 528 FieldPosition& fieldPosition, 529 UErrorCode& status) const; 530 531 /** 532 * Format 2 Calendars to produce a FormattedDateInterval. 533 * 534 * The FormattedDateInterval exposes field information about the formatted string. 535 * 536 * Note: "fromCalendar" and "toCalendar" are not const, 537 * since calendar is not const in SimpleDateFormat::format(Calendar&), 538 * 539 * @param fromCalendar calendar set to the from date in date interval 540 * to be formatted into date interval string 541 * @param toCalendar calendar set to the to date in date interval 542 * to be formatted into date interval string 543 * @param status Set if an error occurs. 544 * @return A FormattedDateInterval containing the format result. 545 * @stable ICU 64 546 */ 547 U_I18N_API FormattedDateInterval formatToValue(Calendar& fromCalendar, 548 Calendar& toCalendar, 549 UErrorCode& status) const; 550 551 /** 552 * Date interval parsing is not supported. Please do not use. 553 * <P> 554 * This method should handle parsing of 555 * date time interval strings into Formattable objects with 556 * DateInterval type, which is a pair of UDate. 557 * <P> 558 * Before calling, set parse_pos.index to the offset you want to start 559 * parsing at in the source. After calling, parse_pos.index is the end of 560 * the text you parsed. If error occurs, index is unchanged. 561 * <P> 562 * When parsing, leading whitespace is discarded (with a successful parse), 563 * while trailing whitespace is left as is. 564 * <P> 565 * See Format::parseObject() for more. 566 * 567 * @param source The string to be parsed into an object. 568 * @param result Formattable to be set to the parse result. 569 * If parse fails, return contents are undefined. 570 * @param parse_pos The position to start parsing at. Since no parsing 571 * is supported, upon return this param is unchanged. 572 * @return A newly created Formattable* object, or nullptr 573 * on failure. The caller owns this and should 574 * delete it when done. 575 * @internal ICU 4.0 576 */ 577 U_I18N_API virtual void parseObject(const UnicodeString& source, 578 Formattable& result, 579 ParsePosition& parse_pos) const override; 580 581 /** 582 * Gets the date time interval patterns. 583 * @return the date time interval patterns associated with 584 * this date interval formatter. 585 * @stable ICU 4.0 586 */ 587 U_I18N_API const DateIntervalInfo* getDateIntervalInfo() const; 588 589 /** 590 * Set the date time interval patterns. 591 * @param newIntervalPatterns the given interval patterns to copy. 592 * @param status output param set to success/failure code on exit 593 * @stable ICU 4.0 594 */ 595 U_I18N_API void setDateIntervalInfo(const DateIntervalInfo& newIntervalPatterns, UErrorCode& status); 596 597 /** 598 * Gets the date formatter. The DateIntervalFormat instance continues to own 599 * the returned DateFormatter object, and will use and possibly modify it 600 * during format operations. In a multi-threaded environment, the returned 601 * DateFormat can only be used if it is certain that no other threads are 602 * concurrently using this DateIntervalFormatter, even for nominally const 603 * functions. 604 * 605 * @return the date formatter associated with this date interval formatter. 606 * @stable ICU 4.0 607 */ 608 U_I18N_API const DateFormat* getDateFormat() const; 609 610 /** 611 * Returns a reference to the TimeZone used by this DateIntervalFormat's calendar. 612 * @return the time zone associated with the calendar of DateIntervalFormat. 613 * @stable ICU 4.8 614 */ 615 U_I18N_API virtual const TimeZone& getTimeZone() const; 616 617 /** 618 * Sets the time zone for the calendar used by this DateIntervalFormat object. The 619 * caller no longer owns the TimeZone object and should not delete it after this call. 620 * @param zoneToAdopt the TimeZone to be adopted. 621 * @stable ICU 4.8 622 */ 623 U_I18N_API virtual void adoptTimeZone(TimeZone* zoneToAdopt); 624 625 /** 626 * Sets the time zone for the calendar used by this DateIntervalFormat object. 627 * @param zone the new time zone. 628 * @stable ICU 4.8 629 */ 630 U_I18N_API virtual void setTimeZone(const TimeZone& zone); 631 632 /** 633 * Sets the calendar used by this DateIntervalFormat object. The caller no longer owns 634 * the Calendar object and should not delete it after this call. 635 * @param calendarToAdopt the Calendar to be adopted. 636 */ 637 U_I18N_API virtual void adoptCalendar(Calendar *calendarToAdopt); 638 639 /** 640 * Set a particular UDisplayContext value in the formatter, such as 641 * UDISPCTX_CAPITALIZATION_FOR_STANDALONE. This causes the formatted 642 * result to be capitalized appropriately for the context in which 643 * it is intended to be used, considering both the locale and the 644 * type of field at the beginning of the formatted result. 645 * @param value The UDisplayContext value to set. 646 * @param status Input/output status. If at entry this indicates a failure 647 * status, the function will do nothing; otherwise this will be 648 * updated with any new status from the function. 649 * @stable ICU 68 650 */ 651 U_I18N_API virtual void setContext(UDisplayContext value, UErrorCode& status); 652 653 /** 654 * Get the formatter's UDisplayContext value for the specified UDisplayContextType, 655 * such as UDISPCTX_TYPE_CAPITALIZATION. 656 * @param type The UDisplayContextType whose value to return 657 * @param status Input/output status. If at entry this indicates a failure 658 * status, the function will do nothing; otherwise this will be 659 * updated with any new status from the function. 660 * @return The UDisplayContextValue for the specified type. 661 * @stable ICU 68 662 */ 663 U_I18N_API virtual UDisplayContext getContext(UDisplayContextType type, UErrorCode& status) const; 664 665 /** 666 * Return the class ID for this class. This is useful only for comparing to 667 * a return value from getDynamicClassID(). For example: 668 * <pre> 669 * . Base* polymorphic_pointer = createPolymorphicObject(); 670 * . if (polymorphic_pointer->getDynamicClassID() == 671 * . erived::getStaticClassID()) ... 672 * </pre> 673 * @return The class ID for all objects of this class. 674 * @stable ICU 4.0 675 */ 676 U_I18N_API static UClassID getStaticClassID(); 677 678 /** 679 * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This 680 * method is to implement a simple version of RTTI, since not all C++ 681 * compilers support genuine RTTI. Polymorphic operator==() and clone() 682 * methods call this method. 683 * 684 * @return The class ID for this object. All objects of a 685 * given class have the same class ID. Objects of 686 * other classes have different class IDs. 687 * @stable ICU 4.0 688 */ 689 U_I18N_API virtual UClassID getDynamicClassID() const override; 690 691 protected: 692 693 /** 694 * Copy constructor. 695 * @stable ICU 4.0 696 */ 697 DateIntervalFormat(const DateIntervalFormat&); 698 699 /** 700 * Assignment operator. 701 * @stable ICU 4.0 702 */ 703 DateIntervalFormat& operator=(const DateIntervalFormat&); 704 705 private: 706 707 /* 708 * This is for ICU internal use only. Please do not use. 709 * Save the interval pattern information. 710 * Interval pattern consists of 2 single date patterns and the separator. 711 * For example, interval pattern "MMM d - MMM d, yyyy" consists 712 * a single date pattern "MMM d", another single date pattern "MMM d, yyyy", 713 * and a separator "-". 714 * The pattern is divided into 2 parts. For above example, 715 * the first part is "MMM d - ", and the second part is "MMM d, yyyy". 716 * Also, the first date appears in an interval pattern could be 717 * the earlier date or the later date. 718 * And such information is saved in the interval pattern as well. 719 */ 720 struct PatternInfo { 721 UnicodeString firstPart; 722 UnicodeString secondPart; 723 /** 724 * Whether the first date in interval pattern is later date or not. 725 * Fallback format set the default ordering. 726 * And for a particular interval pattern, the order can be 727 * overridden by prefixing the interval pattern with "latestFirst:" or 728 * "earliestFirst:" 729 * For example, given 2 date, Jan 10, 2007 to Feb 10, 2007. 730 * if the fallback format is "{0} - {1}", 731 * and the pattern is "d MMM - d MMM yyyy", the interval format is 732 * "10 Jan - 10 Feb, 2007". 733 * If the pattern is "latestFirst:d MMM - d MMM yyyy", 734 * the interval format is "10 Feb - 10 Jan, 2007" 735 */ 736 UBool laterDateFirst; 737 }; 738 739 740 /** 741 * default constructor 742 */ 743 DateIntervalFormat(); 744 745 /** 746 * Construct a DateIntervalFormat from DateFormat, 747 * a DateIntervalInfo, and skeleton. 748 * DateFormat provides the timezone, calendar, 749 * full pattern, and date format symbols information. 750 * It should be a SimpleDateFormat object which 751 * has a pattern in it. 752 * the DateIntervalInfo provides the interval patterns. 753 * 754 * Note: the DateIntervalFormat takes ownership of both 755 * DateFormat and DateIntervalInfo objects. 756 * Caller should not delete them. 757 * 758 * @param locale the locale of this date interval formatter. 759 * @param dtItvInfo the DateIntervalInfo object to be adopted. 760 * @param skeleton the skeleton of the date formatter 761 * @param status output param set to success/failure code on exit 762 */ 763 DateIntervalFormat(const Locale& locale, DateIntervalInfo* dtItvInfo, 764 const UnicodeString* skeleton, UErrorCode& status); 765 766 767 /** 768 * Construct a DateIntervalFormat from DateFormat 769 * and a DateIntervalInfo. 770 * 771 * It is a wrapper of the constructor. 772 * 773 * @param locale the locale of this date interval formatter. 774 * @param dtitvinf the DateIntervalInfo object to be adopted. 775 * @param skeleton the skeleton of this formatter. 776 * @param status Output param set to success/failure code. 777 * @return a date time interval formatter which the caller owns. 778 */ 779 U_I18N_API static DateIntervalFormat* create(const Locale& locale, 780 DateIntervalInfo* dtitvinf, 781 const UnicodeString* skeleton, 782 UErrorCode& status); 783 784 /** 785 * Below are for generating interval patterns local to the formatter 786 */ 787 788 /** Like fallbackFormat, but only formats the range part of the fallback. */ 789 void fallbackFormatRange( 790 Calendar& fromCalendar, 791 Calendar& toCalendar, 792 UnicodeString& appendTo, 793 int8_t& firstIndex, 794 FieldPositionHandler& fphandler, 795 UErrorCode& status) const; 796 797 /** 798 * Format 2 Calendars using fall-back interval pattern 799 * 800 * The full pattern used in this fall-back format is the 801 * full pattern of the date formatter. 802 * 803 * gFormatterMutex must already be locked when calling this function. 804 * 805 * @param fromCalendar calendar set to the from date in date interval 806 * to be formatted into date interval string 807 * @param toCalendar calendar set to the to date in date interval 808 * to be formatted into date interval string 809 * @param fromToOnSameDay true iff from and to dates are on the same day 810 * (any difference is in ampm/hours or below) 811 * @param appendTo Output parameter to receive result. 812 * Result is appended to existing contents. 813 * @param firstIndex See formatImpl for more information. 814 * @param fphandler See formatImpl for more information. 815 * @param status output param set to success/failure code on exit 816 * @return Reference to 'appendTo' parameter. 817 */ 818 UnicodeString& fallbackFormat(Calendar& fromCalendar, 819 Calendar& toCalendar, 820 UBool fromToOnSameDay, 821 UnicodeString& appendTo, 822 int8_t& firstIndex, 823 FieldPositionHandler& fphandler, 824 UErrorCode& status) const; 825 826 827 828 /** 829 * Initialize interval patterns locale to this formatter 830 * 831 * This code is a bit complicated since 832 * 1. the interval patterns saved in resource bundle files are interval 833 * patterns based on date or time only. 834 * It does not have interval patterns based on both date and time. 835 * Interval patterns on both date and time are algorithm generated. 836 * 837 * For example, it has interval patterns on skeleton "dMy" and "hm", 838 * but it does not have interval patterns on skeleton "dMyhm". 839 * 840 * The rule to generate interval patterns for both date and time skeleton are 841 * 1) when the year, month, or day differs, concatenate the two original 842 * expressions with a separator between, 843 * For example, interval pattern from "Jan 10, 2007 10:10 am" 844 * to "Jan 11, 2007 10:10am" is 845 * "Jan 10, 2007 10:10 am - Jan 11, 2007 10:10am" 846 * 847 * 2) otherwise, present the date followed by the range expression 848 * for the time. 849 * For example, interval pattern from "Jan 10, 2007 10:10 am" 850 * to "Jan 10, 2007 11:10am" is 851 * "Jan 10, 2007 10:10 am - 11:10am" 852 * 853 * 2. even a pattern does not request a certain calendar field, 854 * the interval pattern needs to include such field if such fields are 855 * different between 2 dates. 856 * For example, a pattern/skeleton is "hm", but the interval pattern 857 * includes year, month, and date when year, month, and date differs. 858 * 859 * 860 * @param status output param set to success/failure code on exit 861 */ 862 void initializePattern(UErrorCode& status); 863 864 865 866 /** 867 * Set fall back interval pattern given a calendar field, 868 * a skeleton, and a date time pattern generator. 869 * @param field the largest different calendar field 870 * @param skeleton a skeleton 871 * @param status output param set to success/failure code on exit 872 */ 873 void setFallbackPattern(UCalendarDateFields field, 874 const UnicodeString& skeleton, 875 UErrorCode& status); 876 877 878 879 /** 880 * Converts special hour metacharacters (such as 'j') in the skeleton into locale-appropriate 881 * pattern characters. 882 * 883 * 884 * @param skeleton The skeleton to convert 885 * @return A copy of the skeleton, which "j" and any other special hour metacharacters converted to the regular ones. 886 * 887 */ 888 UnicodeString normalizeHourMetacharacters(const UnicodeString& skeleton) const; 889 890 891 892 /** 893 * get separated date and time skeleton from a combined skeleton. 894 * 895 * The difference between date skeleton and normalizedDateSkeleton are: 896 * 1. both 'y' and 'd' are appeared only once in normalizeDateSkeleton 897 * 2. 'E' and 'EE' are normalized into 'EEE' 898 * 3. 'MM' is normalized into 'M' 899 * 900 ** the difference between time skeleton and normalizedTimeSkeleton are: 901 * 1. both 'H' and 'h' are normalized as 'h' in normalized time skeleton, 902 * 2. 'a' is omitted in normalized time skeleton. 903 * 3. there is only one appearance for 'h', 'm','v', 'z' in normalized time 904 * skeleton 905 * 906 * 907 * @param skeleton given combined skeleton. 908 * @param date Output parameter for date only skeleton. 909 * @param normalizedDate Output parameter for normalized date only 910 * 911 * @param time Output parameter for time only skeleton. 912 * @param normalizedTime Output parameter for normalized time only 913 * skeleton. 914 * 915 */ 916 U_I18N_API static void getDateTimeSkeleton(const UnicodeString& skeleton, 917 UnicodeString& date, 918 UnicodeString& normalizedDate, 919 UnicodeString& time, 920 UnicodeString& normalizedTime); 921 922 /** 923 * Generate date or time interval pattern from resource, 924 * and set them into the interval pattern locale to this formatter. 925 * 926 * It needs to handle the following: 927 * 1. need to adjust field width. 928 * For example, the interval patterns saved in DateIntervalInfo 929 * includes "dMMMy", but not "dMMMMy". 930 * Need to get interval patterns for dMMMMy from dMMMy. 931 * Another example, the interval patterns saved in DateIntervalInfo 932 * includes "hmv", but not "hmz". 933 * Need to get interval patterns for "hmz' from 'hmv' 934 * 935 * 2. there might be no pattern for 'y' differ for skeleton "Md", 936 * in order to get interval patterns for 'y' differ, 937 * need to look for it from skeleton 'yMd' 938 * 939 * @param dateSkeleton normalized date skeleton 940 * @param timeSkeleton normalized time skeleton 941 * @return whether the resource is found for the skeleton. 942 * true if interval pattern found for the skeleton, 943 * false otherwise. 944 */ 945 UBool setSeparateDateTimePtn(const UnicodeString& dateSkeleton, 946 const UnicodeString& timeSkeleton); 947 948 949 950 951 /** 952 * Generate interval pattern from existing resource 953 * 954 * It not only save the interval patterns, 955 * but also return the extended skeleton and its best match skeleton. 956 * 957 * @param field largest different calendar field 958 * @param skeleton skeleton 959 * @param bestSkeleton the best match skeleton which has interval pattern 960 * defined in resource 961 * @param differenceInfo the difference between skeleton and best skeleton 962 * 0 means the best matched skeleton is the same as input skeleton 963 * 1 means the fields are the same, but field width are different 964 * 2 means the only difference between fields are v/z, 965 * -1 means there are other fields difference 966 * 967 * @param extendedSkeleton extended skeleton 968 * @param extendedBestSkeleton extended best match skeleton 969 * @return whether the interval pattern is found 970 * through extending skeleton or not. 971 * true if interval pattern is found by 972 * extending skeleton, false otherwise. 973 */ 974 UBool setIntervalPattern(UCalendarDateFields field, 975 const UnicodeString* skeleton, 976 const UnicodeString* bestSkeleton, 977 int8_t differenceInfo, 978 UnicodeString* extendedSkeleton = nullptr, 979 UnicodeString* extendedBestSkeleton = nullptr); 980 981 /** 982 * Adjust field width in best match interval pattern to match 983 * the field width in input skeleton. 984 * 985 * TODO (xji) make a general solution 986 * The adjusting rule can be: 987 * 1. always adjust 988 * 2. never adjust 989 * 3. default adjust, which means adjust according to the following rules 990 * 3.1 always adjust string, such as MMM and MMMM 991 * 3.2 never adjust between string and numeric, such as MM and MMM 992 * 3.3 always adjust year 993 * 3.4 do not adjust 'd', 'h', or 'm' if h presents 994 * 3.5 do not adjust 'M' if it is numeric(?) 995 * 996 * Since date interval format is well-formed format, 997 * date and time skeletons are normalized previously, 998 * till this stage, the adjust here is only "adjust strings, such as MMM 999 * and MMMM, EEE and EEEE. 1000 * 1001 * @param inputSkeleton the input skeleton 1002 * @param bestMatchSkeleton the best match skeleton 1003 * @param bestMatchIntervalPattern the best match interval pattern 1004 * @param differenceInfo the difference between 2 skeletons 1005 * 1 means only field width differs 1006 * 2 means v/z exchange 1007 * @param suppressDayPeriodField if true, remove the day period field from the pattern, if there is one 1008 * @param adjustedIntervalPattern adjusted interval pattern 1009 */ 1010 U_I18N_API static void adjustFieldWidth(const UnicodeString& inputSkeleton, 1011 const UnicodeString& bestMatchSkeleton, 1012 const UnicodeString& bestMatchIntervalPattern, 1013 int8_t differenceInfo, 1014 UBool suppressDayPeriodField, 1015 UnicodeString& adjustedIntervalPattern); 1016 1017 /** 1018 * Does the same thing as UnicodeString::findAndReplace(), except that it won't perform 1019 * the substitution inside quoted literal text. 1020 * @param targetString The string to perform the find-replace operation on. 1021 * @param strToReplace The string to search for and replace in the target string. 1022 * @param strToReplaceWith The string to substitute in wherever `stringToReplace` was found. 1023 */ 1024 U_I18N_API static void findReplaceInPattern(UnicodeString& targetString, 1025 const UnicodeString& strToReplace, 1026 const UnicodeString& strToReplaceWith); 1027 1028 /** 1029 * Concat a single date pattern with a time interval pattern, 1030 * set it into the intervalPatterns, while field is time field. 1031 * This is used to handle time interval patterns on skeleton with 1032 * both time and date. Present the date followed by 1033 * the range expression for the time. 1034 * @param format date and time format 1035 * @param datePattern date pattern 1036 * @param field time calendar field: AM_PM, HOUR, MINUTE 1037 * @param status output param set to success/failure code on exit 1038 */ 1039 void concatSingleDate2TimeInterval(UnicodeString& format, 1040 const UnicodeString& datePattern, 1041 UCalendarDateFields field, 1042 UErrorCode& status); 1043 1044 /** 1045 * check whether a calendar field present in a skeleton. 1046 * @param field calendar field need to check 1047 * @param skeleton given skeleton on which to check the calendar field 1048 * @return true if field present in a skeleton. 1049 */ 1050 U_I18N_API static UBool fieldExistsInSkeleton(UCalendarDateFields field, 1051 const UnicodeString& skeleton); 1052 1053 /** 1054 * Split interval patterns into 2 part. 1055 * @param intervalPattern interval pattern 1056 * @return the index in interval pattern which split the pattern into 2 part 1057 */ 1058 U_I18N_API static int32_t splitPatternInto2Part(const UnicodeString& intervalPattern); 1059 1060 /** 1061 * Break interval patterns as 2 part and save them into pattern info. 1062 * @param field calendar field 1063 * @param intervalPattern interval pattern 1064 */ 1065 void setIntervalPattern(UCalendarDateFields field, 1066 const UnicodeString& intervalPattern); 1067 1068 1069 /** 1070 * Break interval patterns as 2 part and save them into pattern info. 1071 * @param field calendar field 1072 * @param intervalPattern interval pattern 1073 * @param laterDateFirst whether later date appear first in interval pattern 1074 */ 1075 void setIntervalPattern(UCalendarDateFields field, 1076 const UnicodeString& intervalPattern, 1077 UBool laterDateFirst); 1078 1079 1080 /** 1081 * Set pattern information. 1082 * 1083 * @param field calendar field 1084 * @param firstPart the first part in interval pattern 1085 * @param secondPart the second part in interval pattern 1086 * @param laterDateFirst whether the first date in intervalPattern 1087 * is earlier date or later date 1088 */ 1089 void setPatternInfo(UCalendarDateFields field, 1090 const UnicodeString* firstPart, 1091 const UnicodeString* secondPart, 1092 UBool laterDateFirst); 1093 1094 /** 1095 * Format 2 Calendars to produce a string. 1096 * Implementation of the similar public format function. 1097 * Must be called with gFormatterMutex already locked. 1098 * 1099 * Note: "fromCalendar" and "toCalendar" are not const, 1100 * since calendar is not const in SimpleDateFormat::format(Calendar&), 1101 * 1102 * @param fromCalendar calendar set to the from date in date interval 1103 * to be formatted into date interval string 1104 * @param toCalendar calendar set to the to date in date interval 1105 * to be formatted into date interval string 1106 * @param appendTo Output parameter to receive result. 1107 * Result is appended to existing contents. 1108 * @param firstIndex 0 if the first output date is fromCalendar; 1109 * 1 if it corresponds to toCalendar; 1110 * -1 if there is only one date printed. 1111 * @param fphandler Handler for field position information. 1112 * The fields will be from the UDateFormatField enum. 1113 * @param status Output param filled with success/failure status. 1114 * Caller needs to make sure it is SUCCESS 1115 * at the function entrance 1116 * @return Reference to 'appendTo' parameter. 1117 */ 1118 UnicodeString& formatImpl(Calendar& fromCalendar, 1119 Calendar& toCalendar, 1120 UnicodeString& appendTo, 1121 int8_t& firstIndex, 1122 FieldPositionHandler& fphandler, 1123 UErrorCode& status) const ; 1124 1125 /** Version of formatImpl for DateInterval. */ 1126 UnicodeString& formatIntervalImpl(const DateInterval& dtInterval, 1127 UnicodeString& appendTo, 1128 int8_t& firstIndex, 1129 FieldPositionHandler& fphandler, 1130 UErrorCode& status) const; 1131 1132 1133 // from calendar field to pattern letter 1134 static const char16_t fgCalendarFieldToPatternLetter[]; 1135 1136 1137 /** 1138 * The interval patterns for this locale. 1139 */ 1140 DateIntervalInfo* fInfo; 1141 1142 /** 1143 * The DateFormat object used to format single pattern 1144 */ 1145 SimpleDateFormat* fDateFormat; 1146 1147 /** 1148 * The 2 calendars with the from and to date. 1149 * could re-use the calendar in fDateFormat, 1150 * but keeping 2 calendars make it clear and clean. 1151 */ 1152 Calendar* fFromCalendar; 1153 Calendar* fToCalendar; 1154 1155 Locale fLocale; 1156 1157 /** 1158 * Following are interval information relevant (locale) to this formatter. 1159 */ 1160 UnicodeString fSkeleton; 1161 PatternInfo fIntervalPatterns[DateIntervalInfo::kIPI_MAX_INDEX]; 1162 1163 /** 1164 * Patterns for fallback formatting. 1165 */ 1166 UnicodeString* fDatePattern; 1167 UnicodeString* fTimePattern; 1168 UnicodeString* fDateTimeFormat; 1169 1170 /** 1171 * Other formatting information 1172 */ 1173 UDisplayContext fCapitalizationContext; 1174 }; 1175 1176 inline bool 1177 DateIntervalFormat::operator!=(const Format& other) const { 1178 return !operator==(other); 1179 } 1180 1181 U_NAMESPACE_END 1182 1183 #endif /* #if !UCONFIG_NO_FORMATTING */ 1184 1185 #endif /* U_SHOW_CPLUSPLUS_API */ 1186 1187 #endif // _DTITVFMT_H__ 1188 //eof