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 */ FormattedDateInterval()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; FormattedDateInterval(FormattedDateIntervalData * results)106 explicit FormattedDateInterval(FormattedDateIntervalData *results) 107 : fData(results), fErrorCode(U_ZERO_ERROR) {} FormattedDateInterval(UErrorCode errorCode)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 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 static DateIntervalFormat* U_EXPORT2 createInstance( 317 const UnicodeString& skeleton, 318 UErrorCode& status); 319 320 /** 321 * Construct a DateIntervalFormat from skeleton and a given locale. 322 * <P> 323 * In this factory method, 324 * the date interval pattern information is load from resource files. 325 * Users are encouraged to created date interval formatter this way and 326 * to use the pre-defined skeleton macros. 327 * 328 * <P> 329 * There are pre-defined skeletons (defined in udate.h) having predefined 330 * interval patterns in resource files. 331 * Users are encouraged to use those macros. 332 * For example: 333 * DateIntervalFormat::createInstance(UDAT_MONTH_DAY, status) 334 * 335 * The given Locale provides the interval patterns. 336 * For example, for en_GB, if skeleton is UDAT_YEAR_ABBR_MONTH_WEEKDAY_DAY, 337 * which is "yMMMEEEd", 338 * the interval patterns defined in resource file to above skeleton are: 339 * "EEE, d MMM, yyyy - EEE, d MMM, yyyy" for year differs, 340 * "EEE, d MMM - EEE, d MMM, yyyy" for month differs, 341 * "EEE, d - EEE, d MMM, yyyy" for day differs, 342 * @param skeleton the skeleton on which the interval format is based. 343 * @param locale the given locale 344 * @param status output param set to success/failure code on exit 345 * @return a date time interval formatter which the caller owns. 346 * @stable ICU 4.0 347 */ 348 349 static DateIntervalFormat* U_EXPORT2 createInstance( 350 const UnicodeString& skeleton, 351 const Locale& locale, 352 UErrorCode& status); 353 354 /** 355 * Construct a DateIntervalFormat from skeleton 356 * DateIntervalInfo, and default locale. 357 * 358 * This is a convenient override of 359 * createInstance(const UnicodeString& skeleton, const Locale& locale, 360 * const DateIntervalInfo& dtitvinf, UErrorCode&) 361 * with the locale value as default locale. 362 * 363 * @param skeleton the skeleton on which interval format based. 364 * @param dtitvinf the DateIntervalInfo object. 365 * @param status output param set to success/failure code on exit 366 * @return a date time interval formatter which the caller owns. 367 * @stable ICU 4.0 368 */ 369 static DateIntervalFormat* U_EXPORT2 createInstance( 370 const UnicodeString& skeleton, 371 const DateIntervalInfo& dtitvinf, 372 UErrorCode& status); 373 374 /** 375 * Construct a DateIntervalFormat from skeleton 376 * a DateIntervalInfo, and the given locale. 377 * 378 * <P> 379 * In this factory method, user provides its own date interval pattern 380 * information, instead of using those pre-defined data in resource file. 381 * This factory method is for powerful users who want to provide their own 382 * interval patterns. 383 * <P> 384 * There are pre-defined skeletons (defined in udate.h) having predefined 385 * interval patterns in resource files. 386 * Users are encouraged to use those macros. 387 * For example: 388 * DateIntervalFormat::createInstance(UDAT_MONTH_DAY, status) 389 * 390 * The DateIntervalInfo provides the interval patterns. 391 * and the DateIntervalInfo ownership remains to the caller. 392 * 393 * User are encouraged to set default interval pattern in DateIntervalInfo 394 * as well, if they want to set other interval patterns ( instead of 395 * reading the interval patterns from resource files). 396 * When the corresponding interval pattern for a largest calendar different 397 * field is not found ( if user not set it ), interval format fallback to 398 * the default interval pattern. 399 * If user does not provide default interval pattern, it fallback to 400 * "{date0} - {date1}" 401 * 402 * @param skeleton the skeleton on which interval format based. 403 * @param locale the given locale 404 * @param dtitvinf the DateIntervalInfo object. 405 * @param status output param set to success/failure code on exit 406 * @return a date time interval formatter which the caller owns. 407 * @stable ICU 4.0 408 */ 409 static DateIntervalFormat* U_EXPORT2 createInstance( 410 const UnicodeString& skeleton, 411 const Locale& locale, 412 const DateIntervalInfo& dtitvinf, 413 UErrorCode& status); 414 415 /** 416 * Destructor. 417 * @stable ICU 4.0 418 */ 419 virtual ~DateIntervalFormat(); 420 421 /** 422 * Clone this Format object polymorphically. The caller owns the result and 423 * should delete it when done. 424 * @return A copy of the object. 425 * @stable ICU 4.0 426 */ 427 virtual DateIntervalFormat* clone() const override; 428 429 /** 430 * Return true if the given Format objects are semantically equal. Objects 431 * of different subclasses are considered unequal. 432 * @param other the object to be compared with. 433 * @return true if the given Format objects are semantically equal. 434 * @stable ICU 4.0 435 */ 436 virtual bool operator==(const Format& other) const override; 437 438 /** 439 * Return true if the given Format objects are not semantically equal. 440 * Objects of different subclasses are considered unequal. 441 * @param other the object to be compared with. 442 * @return true if the given Format objects are not semantically equal. 443 * @stable ICU 4.0 444 */ 445 bool operator!=(const Format& other) const; 446 447 448 using Format::format; 449 450 /** 451 * Format an object to produce a string. This method handles Formattable 452 * objects with a DateInterval type. 453 * If a the Formattable object type is not a DateInterval, 454 * then it returns a failing UErrorCode. 455 * 456 * @param obj The object to format. 457 * Must be a DateInterval. 458 * @param appendTo Output parameter to receive result. 459 * Result is appended to existing contents. 460 * @param fieldPosition On input: an alignment field, if desired. 461 * On output: the offsets of the alignment field. 462 * There may be multiple instances of a given field type 463 * in an interval format; in this case the fieldPosition 464 * offsets refer to the first instance. 465 * @param status Output param filled with success/failure status. 466 * @return Reference to 'appendTo' parameter. 467 * @stable ICU 4.0 468 */ 469 virtual UnicodeString& format(const Formattable& obj, 470 UnicodeString& appendTo, 471 FieldPosition& fieldPosition, 472 UErrorCode& status) const override; 473 474 475 476 /** 477 * Format a DateInterval to produce a string. 478 * 479 * @param dtInterval DateInterval to be formatted. 480 * @param appendTo Output parameter to receive result. 481 * Result is appended to existing contents. 482 * @param fieldPosition On input: an alignment field, if desired. 483 * On output: the offsets of the alignment field. 484 * There may be multiple instances of a given field type 485 * in an interval format; in this case the fieldPosition 486 * offsets refer to the first instance. 487 * @param status Output param filled with success/failure status. 488 * @return Reference to 'appendTo' parameter. 489 * @stable ICU 4.0 490 */ 491 UnicodeString& format(const DateInterval* dtInterval, 492 UnicodeString& appendTo, 493 FieldPosition& fieldPosition, 494 UErrorCode& status) const ; 495 496 /** 497 * Format a DateInterval to produce a FormattedDateInterval. 498 * 499 * The FormattedDateInterval exposes field information about the formatted string. 500 * 501 * @param dtInterval DateInterval to be formatted. 502 * @param status Set if an error occurs. 503 * @return A FormattedDateInterval containing the format result. 504 * @stable ICU 64 505 */ 506 FormattedDateInterval formatToValue( 507 const DateInterval& dtInterval, 508 UErrorCode& status) const; 509 510 /** 511 * Format 2 Calendars to produce a string. 512 * 513 * Note: "fromCalendar" and "toCalendar" are not const, 514 * since calendar is not const in SimpleDateFormat::format(Calendar&), 515 * 516 * @param fromCalendar calendar set to the from date in date interval 517 * to be formatted into date interval string 518 * @param toCalendar calendar set to the to date in date interval 519 * to be formatted into date interval string 520 * @param appendTo Output parameter to receive result. 521 * Result is appended to existing contents. 522 * @param fieldPosition On input: an alignment field, if desired. 523 * On output: the offsets of the alignment field. 524 * There may be multiple instances of a given field type 525 * in an interval format; in this case the fieldPosition 526 * offsets refer to the first instance. 527 * @param status Output param filled with success/failure status. 528 * Caller needs to make sure it is SUCCESS 529 * at the function entrance 530 * @return Reference to 'appendTo' parameter. 531 * @stable ICU 4.0 532 */ 533 UnicodeString& format(Calendar& fromCalendar, 534 Calendar& toCalendar, 535 UnicodeString& appendTo, 536 FieldPosition& fieldPosition, 537 UErrorCode& status) const ; 538 539 /** 540 * Format 2 Calendars to produce a FormattedDateInterval. 541 * 542 * The FormattedDateInterval exposes field information about the formatted string. 543 * 544 * Note: "fromCalendar" and "toCalendar" are not const, 545 * since calendar is not const in SimpleDateFormat::format(Calendar&), 546 * 547 * @param fromCalendar calendar set to the from date in date interval 548 * to be formatted into date interval string 549 * @param toCalendar calendar set to the to date in date interval 550 * to be formatted into date interval string 551 * @param status Set if an error occurs. 552 * @return A FormattedDateInterval containing the format result. 553 * @stable ICU 64 554 */ 555 FormattedDateInterval formatToValue( 556 Calendar& fromCalendar, 557 Calendar& toCalendar, 558 UErrorCode& status) const; 559 560 /** 561 * Date interval parsing is not supported. Please do not use. 562 * <P> 563 * This method should handle parsing of 564 * date time interval strings into Formattable objects with 565 * DateInterval type, which is a pair of UDate. 566 * <P> 567 * Before calling, set parse_pos.index to the offset you want to start 568 * parsing at in the source. After calling, parse_pos.index is the end of 569 * the text you parsed. If error occurs, index is unchanged. 570 * <P> 571 * When parsing, leading whitespace is discarded (with a successful parse), 572 * while trailing whitespace is left as is. 573 * <P> 574 * See Format::parseObject() for more. 575 * 576 * @param source The string to be parsed into an object. 577 * @param result Formattable to be set to the parse result. 578 * If parse fails, return contents are undefined. 579 * @param parse_pos The position to start parsing at. Since no parsing 580 * is supported, upon return this param is unchanged. 581 * @return A newly created Formattable* object, or nullptr 582 * on failure. The caller owns this and should 583 * delete it when done. 584 * @internal ICU 4.0 585 */ 586 virtual void parseObject(const UnicodeString& source, 587 Formattable& result, 588 ParsePosition& parse_pos) const override; 589 590 591 /** 592 * Gets the date time interval patterns. 593 * @return the date time interval patterns associated with 594 * this date interval formatter. 595 * @stable ICU 4.0 596 */ 597 const DateIntervalInfo* getDateIntervalInfo() const; 598 599 /** 600 * Set the date time interval patterns. 601 * @param newIntervalPatterns the given interval patterns to copy. 602 * @param status output param set to success/failure code on exit 603 * @stable ICU 4.0 604 */ 605 void setDateIntervalInfo(const DateIntervalInfo& newIntervalPatterns, 606 UErrorCode& status); 607 608 609 /** 610 * Gets the date formatter. The DateIntervalFormat instance continues to own 611 * the returned DateFormatter object, and will use and possibly modify it 612 * during format operations. In a multi-threaded environment, the returned 613 * DateFormat can only be used if it is certain that no other threads are 614 * concurrently using this DateIntervalFormatter, even for nominally const 615 * functions. 616 * 617 * @return the date formatter associated with this date interval formatter. 618 * @stable ICU 4.0 619 */ 620 const DateFormat* getDateFormat() const; 621 622 /** 623 * Returns a reference to the TimeZone used by this DateIntervalFormat's calendar. 624 * @return the time zone associated with the calendar of DateIntervalFormat. 625 * @stable ICU 4.8 626 */ 627 virtual const TimeZone& getTimeZone() const; 628 629 /** 630 * Sets the time zone for the calendar used by this DateIntervalFormat object. The 631 * caller no longer owns the TimeZone object and should not delete it after this call. 632 * @param zoneToAdopt the TimeZone to be adopted. 633 * @stable ICU 4.8 634 */ 635 virtual void adoptTimeZone(TimeZone* zoneToAdopt); 636 637 /** 638 * Sets the time zone for the calendar used by this DateIntervalFormat object. 639 * @param zone the new time zone. 640 * @stable ICU 4.8 641 */ 642 virtual void setTimeZone(const TimeZone& zone); 643 644 /** 645 * Set a particular UDisplayContext value in the formatter, such as 646 * UDISPCTX_CAPITALIZATION_FOR_STANDALONE. This causes the formatted 647 * result to be capitalized appropriately for the context in which 648 * it is intended to be used, considering both the locale and the 649 * type of field at the beginning of the formatted result. 650 * @param value The UDisplayContext value to set. 651 * @param status Input/output status. If at entry this indicates a failure 652 * status, the function will do nothing; otherwise this will be 653 * updated with any new status from the function. 654 * @stable ICU 68 655 */ 656 virtual void setContext(UDisplayContext value, UErrorCode& status); 657 658 /** 659 * Get the formatter's UDisplayContext value for the specified UDisplayContextType, 660 * such as UDISPCTX_TYPE_CAPITALIZATION. 661 * @param type The UDisplayContextType whose value to return 662 * @param status Input/output status. If at entry this indicates a failure 663 * status, the function will do nothing; otherwise this will be 664 * updated with any new status from the function. 665 * @return The UDisplayContextValue for the specified type. 666 * @stable ICU 68 667 */ 668 virtual UDisplayContext getContext(UDisplayContextType type, UErrorCode& status) const; 669 670 /** 671 * Return the class ID for this class. This is useful only for comparing to 672 * a return value from getDynamicClassID(). For example: 673 * <pre> 674 * . Base* polymorphic_pointer = createPolymorphicObject(); 675 * . if (polymorphic_pointer->getDynamicClassID() == 676 * . erived::getStaticClassID()) ... 677 * </pre> 678 * @return The class ID for all objects of this class. 679 * @stable ICU 4.0 680 */ 681 static UClassID U_EXPORT2 getStaticClassID(); 682 683 /** 684 * Returns a unique class ID POLYMORPHICALLY. Pure virtual override. This 685 * method is to implement a simple version of RTTI, since not all C++ 686 * compilers support genuine RTTI. Polymorphic operator==() and clone() 687 * methods call this method. 688 * 689 * @return The class ID for this object. All objects of a 690 * given class have the same class ID. Objects of 691 * other classes have different class IDs. 692 * @stable ICU 4.0 693 */ 694 virtual UClassID getDynamicClassID() const override; 695 696 protected: 697 698 /** 699 * Copy constructor. 700 * @stable ICU 4.0 701 */ 702 DateIntervalFormat(const DateIntervalFormat&); 703 704 /** 705 * Assignment operator. 706 * @stable ICU 4.0 707 */ 708 DateIntervalFormat& operator=(const DateIntervalFormat&); 709 710 private: 711 712 /* 713 * This is for ICU internal use only. Please do not use. 714 * Save the interval pattern information. 715 * Interval pattern consists of 2 single date patterns and the separator. 716 * For example, interval pattern "MMM d - MMM d, yyyy" consists 717 * a single date pattern "MMM d", another single date pattern "MMM d, yyyy", 718 * and a separator "-". 719 * The pattern is divided into 2 parts. For above example, 720 * the first part is "MMM d - ", and the second part is "MMM d, yyyy". 721 * Also, the first date appears in an interval pattern could be 722 * the earlier date or the later date. 723 * And such information is saved in the interval pattern as well. 724 */ 725 struct PatternInfo { 726 UnicodeString firstPart; 727 UnicodeString secondPart; 728 /** 729 * Whether the first date in interval pattern is later date or not. 730 * Fallback format set the default ordering. 731 * And for a particular interval pattern, the order can be 732 * overridden by prefixing the interval pattern with "latestFirst:" or 733 * "earliestFirst:" 734 * For example, given 2 date, Jan 10, 2007 to Feb 10, 2007. 735 * if the fallback format is "{0} - {1}", 736 * and the pattern is "d MMM - d MMM yyyy", the interval format is 737 * "10 Jan - 10 Feb, 2007". 738 * If the pattern is "latestFirst:d MMM - d MMM yyyy", 739 * the interval format is "10 Feb - 10 Jan, 2007" 740 */ 741 UBool laterDateFirst; 742 }; 743 744 745 /** 746 * default constructor 747 * @internal (private) 748 */ 749 DateIntervalFormat(); 750 751 /** 752 * Construct a DateIntervalFormat from DateFormat, 753 * a DateIntervalInfo, and skeleton. 754 * DateFormat provides the timezone, calendar, 755 * full pattern, and date format symbols information. 756 * It should be a SimpleDateFormat object which 757 * has a pattern in it. 758 * the DateIntervalInfo provides the interval patterns. 759 * 760 * Note: the DateIntervalFormat takes ownership of both 761 * DateFormat and DateIntervalInfo objects. 762 * Caller should not delete them. 763 * 764 * @param locale the locale of this date interval formatter. 765 * @param dtItvInfo the DateIntervalInfo object to be adopted. 766 * @param skeleton the skeleton of the date formatter 767 * @param status output param set to success/failure code on exit 768 */ 769 DateIntervalFormat(const Locale& locale, DateIntervalInfo* dtItvInfo, 770 const UnicodeString* skeleton, UErrorCode& status); 771 772 773 /** 774 * Construct a DateIntervalFormat from DateFormat 775 * and a DateIntervalInfo. 776 * 777 * It is a wrapper of the constructor. 778 * 779 * @param locale the locale of this date interval formatter. 780 * @param dtitvinf the DateIntervalInfo object to be adopted. 781 * @param skeleton the skeleton of this formatter. 782 * @param status Output param set to success/failure code. 783 * @return a date time interval formatter which the caller owns. 784 */ 785 static DateIntervalFormat* U_EXPORT2 create(const Locale& locale, 786 DateIntervalInfo* dtitvinf, 787 const UnicodeString* skeleton, 788 UErrorCode& status); 789 790 /** 791 * Below are for generating interval patterns local to the formatter 792 */ 793 794 /** Like fallbackFormat, but only formats the range part of the fallback. */ 795 void fallbackFormatRange( 796 Calendar& fromCalendar, 797 Calendar& toCalendar, 798 UnicodeString& appendTo, 799 int8_t& firstIndex, 800 FieldPositionHandler& fphandler, 801 UErrorCode& status) const; 802 803 /** 804 * Format 2 Calendars using fall-back interval pattern 805 * 806 * The full pattern used in this fall-back format is the 807 * full pattern of the date formatter. 808 * 809 * gFormatterMutex must already be locked when calling this function. 810 * 811 * @param fromCalendar calendar set to the from date in date interval 812 * to be formatted into date interval string 813 * @param toCalendar calendar set to the to date in date interval 814 * to be formatted into date interval string 815 * @param fromToOnSameDay true iff from and to dates are on the same day 816 * (any difference is in ampm/hours or below) 817 * @param appendTo Output parameter to receive result. 818 * Result is appended to existing contents. 819 * @param firstIndex See formatImpl for more information. 820 * @param fphandler See formatImpl for more information. 821 * @param status output param set to success/failure code on exit 822 * @return Reference to 'appendTo' parameter. 823 * @internal (private) 824 */ 825 UnicodeString& fallbackFormat(Calendar& fromCalendar, 826 Calendar& toCalendar, 827 UBool fromToOnSameDay, 828 UnicodeString& appendTo, 829 int8_t& firstIndex, 830 FieldPositionHandler& fphandler, 831 UErrorCode& status) const; 832 833 834 835 /** 836 * Initialize interval patterns locale to this formatter 837 * 838 * This code is a bit complicated since 839 * 1. the interval patterns saved in resource bundle files are interval 840 * patterns based on date or time only. 841 * It does not have interval patterns based on both date and time. 842 * Interval patterns on both date and time are algorithm generated. 843 * 844 * For example, it has interval patterns on skeleton "dMy" and "hm", 845 * but it does not have interval patterns on skeleton "dMyhm". 846 * 847 * The rule to generate interval patterns for both date and time skeleton are 848 * 1) when the year, month, or day differs, concatenate the two original 849 * expressions with a separator between, 850 * For example, interval pattern from "Jan 10, 2007 10:10 am" 851 * to "Jan 11, 2007 10:10am" is 852 * "Jan 10, 2007 10:10 am - Jan 11, 2007 10:10am" 853 * 854 * 2) otherwise, present the date followed by the range expression 855 * for the time. 856 * For example, interval pattern from "Jan 10, 2007 10:10 am" 857 * to "Jan 10, 2007 11:10am" is 858 * "Jan 10, 2007 10:10 am - 11:10am" 859 * 860 * 2. even a pattern does not request a certain calendar field, 861 * the interval pattern needs to include such field if such fields are 862 * different between 2 dates. 863 * For example, a pattern/skeleton is "hm", but the interval pattern 864 * includes year, month, and date when year, month, and date differs. 865 * 866 * 867 * @param status output param set to success/failure code on exit 868 */ 869 void initializePattern(UErrorCode& status); 870 871 872 873 /** 874 * Set fall back interval pattern given a calendar field, 875 * a skeleton, and a date time pattern generator. 876 * @param field the largest different calendar field 877 * @param skeleton a skeleton 878 * @param status output param set to success/failure code on exit 879 */ 880 void setFallbackPattern(UCalendarDateFields field, 881 const UnicodeString& skeleton, 882 UErrorCode& status); 883 884 885 886 /** 887 * Converts special hour metacharacters (such as 'j') in the skeleton into locale-appropriate 888 * pattern characters. 889 * 890 * 891 * @param skeleton The skeleton to convert 892 * @return A copy of the skeleton, which "j" and any other special hour metacharacters converted to the regular ones. 893 * 894 */ 895 UnicodeString normalizeHourMetacharacters(const UnicodeString& skeleton) const; 896 897 898 899 /** 900 * get separated date and time skeleton from a combined skeleton. 901 * 902 * The difference between date skeleton and normalizedDateSkeleton are: 903 * 1. both 'y' and 'd' are appeared only once in normalizeDateSkeleton 904 * 2. 'E' and 'EE' are normalized into 'EEE' 905 * 3. 'MM' is normalized into 'M' 906 * 907 ** the difference between time skeleton and normalizedTimeSkeleton are: 908 * 1. both 'H' and 'h' are normalized as 'h' in normalized time skeleton, 909 * 2. 'a' is omitted in normalized time skeleton. 910 * 3. there is only one appearance for 'h', 'm','v', 'z' in normalized time 911 * skeleton 912 * 913 * 914 * @param skeleton given combined skeleton. 915 * @param date Output parameter for date only skeleton. 916 * @param normalizedDate Output parameter for normalized date only 917 * 918 * @param time Output parameter for time only skeleton. 919 * @param normalizedTime Output parameter for normalized time only 920 * skeleton. 921 * 922 */ 923 static void U_EXPORT2 getDateTimeSkeleton(const UnicodeString& skeleton, 924 UnicodeString& date, 925 UnicodeString& normalizedDate, 926 UnicodeString& time, 927 UnicodeString& normalizedTime); 928 929 930 931 /** 932 * Generate date or time interval pattern from resource, 933 * and set them into the interval pattern locale to this formatter. 934 * 935 * It needs to handle the following: 936 * 1. need to adjust field width. 937 * For example, the interval patterns saved in DateIntervalInfo 938 * includes "dMMMy", but not "dMMMMy". 939 * Need to get interval patterns for dMMMMy from dMMMy. 940 * Another example, the interval patterns saved in DateIntervalInfo 941 * includes "hmv", but not "hmz". 942 * Need to get interval patterns for "hmz' from 'hmv' 943 * 944 * 2. there might be no pattern for 'y' differ for skeleton "Md", 945 * in order to get interval patterns for 'y' differ, 946 * need to look for it from skeleton 'yMd' 947 * 948 * @param dateSkeleton normalized date skeleton 949 * @param timeSkeleton normalized time skeleton 950 * @return whether the resource is found for the skeleton. 951 * true if interval pattern found for the skeleton, 952 * false otherwise. 953 */ 954 UBool setSeparateDateTimePtn(const UnicodeString& dateSkeleton, 955 const UnicodeString& timeSkeleton); 956 957 958 959 960 /** 961 * Generate interval pattern from existing resource 962 * 963 * It not only save the interval patterns, 964 * but also return the extended skeleton and its best match skeleton. 965 * 966 * @param field largest different calendar field 967 * @param skeleton skeleton 968 * @param bestSkeleton the best match skeleton which has interval pattern 969 * defined in resource 970 * @param differenceInfo the difference between skeleton and best skeleton 971 * 0 means the best matched skeleton is the same as input skeleton 972 * 1 means the fields are the same, but field width are different 973 * 2 means the only difference between fields are v/z, 974 * -1 means there are other fields difference 975 * 976 * @param extendedSkeleton extended skeleton 977 * @param extendedBestSkeleton extended best match skeleton 978 * @return whether the interval pattern is found 979 * through extending skeleton or not. 980 * true if interval pattern is found by 981 * extending skeleton, false otherwise. 982 */ 983 UBool setIntervalPattern(UCalendarDateFields field, 984 const UnicodeString* skeleton, 985 const UnicodeString* bestSkeleton, 986 int8_t differenceInfo, 987 UnicodeString* extendedSkeleton = nullptr, 988 UnicodeString* extendedBestSkeleton = nullptr); 989 990 /** 991 * Adjust field width in best match interval pattern to match 992 * the field width in input skeleton. 993 * 994 * TODO (xji) make a general solution 995 * The adjusting rule can be: 996 * 1. always adjust 997 * 2. never adjust 998 * 3. default adjust, which means adjust according to the following rules 999 * 3.1 always adjust string, such as MMM and MMMM 1000 * 3.2 never adjust between string and numeric, such as MM and MMM 1001 * 3.3 always adjust year 1002 * 3.4 do not adjust 'd', 'h', or 'm' if h presents 1003 * 3.5 do not adjust 'M' if it is numeric(?) 1004 * 1005 * Since date interval format is well-formed format, 1006 * date and time skeletons are normalized previously, 1007 * till this stage, the adjust here is only "adjust strings, such as MMM 1008 * and MMMM, EEE and EEEE. 1009 * 1010 * @param inputSkeleton the input skeleton 1011 * @param bestMatchSkeleton the best match skeleton 1012 * @param bestMatchIntervalPattern the best match interval pattern 1013 * @param differenceInfo the difference between 2 skeletons 1014 * 1 means only field width differs 1015 * 2 means v/z exchange 1016 * @param suppressDayPeriodField if true, remove the day period field from the pattern, if there is one 1017 * @param adjustedIntervalPattern adjusted interval pattern 1018 */ 1019 static void U_EXPORT2 adjustFieldWidth( 1020 const UnicodeString& inputSkeleton, 1021 const UnicodeString& bestMatchSkeleton, 1022 const UnicodeString& bestMatchIntervalPattern, 1023 int8_t differenceInfo, 1024 UBool suppressDayPeriodField, 1025 UnicodeString& adjustedIntervalPattern); 1026 1027 /** 1028 * Does the same thing as UnicodeString::findAndReplace(), except that it won't perform 1029 * the substitution inside quoted literal text. 1030 * @param targetString The string to perform the find-replace operation on. 1031 * @param strToReplace The string to search for and replace in the target string. 1032 * @param strToReplaceWith The string to substitute in wherever `stringToReplace` was found. 1033 */ 1034 static void U_EXPORT2 findReplaceInPattern(UnicodeString& targetString, 1035 const UnicodeString& strToReplace, 1036 const UnicodeString& strToReplaceWith); 1037 1038 /** 1039 * Concat a single date pattern with a time interval pattern, 1040 * set it into the intervalPatterns, while field is time field. 1041 * This is used to handle time interval patterns on skeleton with 1042 * both time and date. Present the date followed by 1043 * the range expression for the time. 1044 * @param format date and time format 1045 * @param datePattern date pattern 1046 * @param field time calendar field: AM_PM, HOUR, MINUTE 1047 * @param status output param set to success/failure code on exit 1048 */ 1049 void concatSingleDate2TimeInterval(UnicodeString& format, 1050 const UnicodeString& datePattern, 1051 UCalendarDateFields field, 1052 UErrorCode& status); 1053 1054 /** 1055 * check whether a calendar field present in a skeleton. 1056 * @param field calendar field need to check 1057 * @param skeleton given skeleton on which to check the calendar field 1058 * @return true if field present in a skeleton. 1059 */ 1060 static UBool U_EXPORT2 fieldExistsInSkeleton(UCalendarDateFields field, 1061 const UnicodeString& skeleton); 1062 1063 1064 /** 1065 * Split interval patterns into 2 part. 1066 * @param intervalPattern interval pattern 1067 * @return the index in interval pattern which split the pattern into 2 part 1068 */ 1069 static int32_t U_EXPORT2 splitPatternInto2Part(const UnicodeString& intervalPattern); 1070 1071 1072 /** 1073 * Break interval patterns as 2 part and save them into pattern info. 1074 * @param field calendar field 1075 * @param intervalPattern interval pattern 1076 */ 1077 void setIntervalPattern(UCalendarDateFields field, 1078 const UnicodeString& intervalPattern); 1079 1080 1081 /** 1082 * Break interval patterns as 2 part and save them into pattern info. 1083 * @param field calendar field 1084 * @param intervalPattern interval pattern 1085 * @param laterDateFirst whether later date appear first in interval pattern 1086 */ 1087 void setIntervalPattern(UCalendarDateFields field, 1088 const UnicodeString& intervalPattern, 1089 UBool laterDateFirst); 1090 1091 1092 /** 1093 * Set pattern information. 1094 * 1095 * @param field calendar field 1096 * @param firstPart the first part in interval pattern 1097 * @param secondPart the second part in interval pattern 1098 * @param laterDateFirst whether the first date in intervalPattern 1099 * is earlier date or later date 1100 */ 1101 void setPatternInfo(UCalendarDateFields field, 1102 const UnicodeString* firstPart, 1103 const UnicodeString* secondPart, 1104 UBool laterDateFirst); 1105 1106 /** 1107 * Format 2 Calendars to produce a string. 1108 * Implementation of the similar public format function. 1109 * Must be called with gFormatterMutex already locked. 1110 * 1111 * Note: "fromCalendar" and "toCalendar" are not const, 1112 * since calendar is not const in SimpleDateFormat::format(Calendar&), 1113 * 1114 * @param fromCalendar calendar set to the from date in date interval 1115 * to be formatted into date interval string 1116 * @param toCalendar calendar set to the to date in date interval 1117 * to be formatted into date interval string 1118 * @param appendTo Output parameter to receive result. 1119 * Result is appended to existing contents. 1120 * @param firstIndex 0 if the first output date is fromCalendar; 1121 * 1 if it corresponds to toCalendar; 1122 * -1 if there is only one date printed. 1123 * @param fphandler Handler for field position information. 1124 * The fields will be from the UDateFormatField enum. 1125 * @param status Output param filled with success/failure status. 1126 * Caller needs to make sure it is SUCCESS 1127 * at the function entrance 1128 * @return Reference to 'appendTo' parameter. 1129 * @internal (private) 1130 */ 1131 UnicodeString& formatImpl(Calendar& fromCalendar, 1132 Calendar& toCalendar, 1133 UnicodeString& appendTo, 1134 int8_t& firstIndex, 1135 FieldPositionHandler& fphandler, 1136 UErrorCode& status) const ; 1137 1138 /** Version of formatImpl for DateInterval. */ 1139 UnicodeString& formatIntervalImpl(const DateInterval& dtInterval, 1140 UnicodeString& appendTo, 1141 int8_t& firstIndex, 1142 FieldPositionHandler& fphandler, 1143 UErrorCode& status) const; 1144 1145 1146 // from calendar field to pattern letter 1147 static const char16_t fgCalendarFieldToPatternLetter[]; 1148 1149 1150 /** 1151 * The interval patterns for this locale. 1152 */ 1153 DateIntervalInfo* fInfo; 1154 1155 /** 1156 * The DateFormat object used to format single pattern 1157 */ 1158 SimpleDateFormat* fDateFormat; 1159 1160 /** 1161 * The 2 calendars with the from and to date. 1162 * could re-use the calendar in fDateFormat, 1163 * but keeping 2 calendars make it clear and clean. 1164 */ 1165 Calendar* fFromCalendar; 1166 Calendar* fToCalendar; 1167 1168 Locale fLocale; 1169 1170 /** 1171 * Following are interval information relevant (locale) to this formatter. 1172 */ 1173 UnicodeString fSkeleton; 1174 PatternInfo fIntervalPatterns[DateIntervalInfo::kIPI_MAX_INDEX]; 1175 1176 /** 1177 * Patterns for fallback formatting. 1178 */ 1179 UnicodeString* fDatePattern; 1180 UnicodeString* fTimePattern; 1181 UnicodeString* fDateTimeFormat; 1182 1183 /** 1184 * Other formatting information 1185 */ 1186 UDisplayContext fCapitalizationContext; 1187 }; 1188 1189 inline bool 1190 DateIntervalFormat::operator!=(const Format& other) const { 1191 return !operator==(other); 1192 } 1193 1194 U_NAMESPACE_END 1195 1196 #endif /* #if !UCONFIG_NO_FORMATTING */ 1197 1198 #endif /* U_SHOW_CPLUSPLUS_API */ 1199 1200 #endif // _DTITVFMT_H__ 1201 //eof 1202