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