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.CPP
9 *
10 *******************************************************************************
11 */
12
13 #include "utypeinfo.h" // for 'typeid' to work
14
15 #include "unicode/dtitvfmt.h"
16
17 #if !UCONFIG_NO_FORMATTING
18
19 //TODO: put in compilation
20 //#define DTITVFMT_DEBUG 1
21
22 #include "unicode/calendar.h"
23 #include "unicode/dtptngen.h"
24 #include "unicode/dtitvinf.h"
25 #include "unicode/simpleformatter.h"
26 #include "unicode/udisplaycontext.h"
27 #include "cmemory.h"
28 #include "cstring.h"
29 #include "dtitv_impl.h"
30 #include "mutex.h"
31 #include "uresimp.h"
32 #include "formattedval_impl.h"
33
34 #ifdef DTITVFMT_DEBUG
35 #include <iostream>
36 #endif
37
38 U_NAMESPACE_BEGIN
39
40
41
42 #ifdef DTITVFMT_DEBUG
43 #define PRINTMESG(msg) { std::cout << "(" << __FILE__ << ":" << __LINE__ << ") " << msg << "\n"; }
44 #endif
45
46
47 static const UChar gDateFormatSkeleton[][11] = {
48 //yMMMMEEEEd
49 {LOW_Y, CAP_M, CAP_M, CAP_M, CAP_M, CAP_E, CAP_E, CAP_E, CAP_E, LOW_D, 0},
50 //yMMMMd
51 {LOW_Y, CAP_M, CAP_M, CAP_M, CAP_M, LOW_D, 0},
52 //yMMMd
53 {LOW_Y, CAP_M, CAP_M, CAP_M, LOW_D, 0},
54 //yMd
55 {LOW_Y, CAP_M, LOW_D, 0} };
56
57
58 static const char gCalendarTag[] = "calendar";
59 static const char gGregorianTag[] = "gregorian";
60 static const char gDateTimePatternsTag[] = "DateTimePatterns";
61
62
63 // latestFirst:
64 static const UChar gLaterFirstPrefix[] = {LOW_L, LOW_A, LOW_T, LOW_E, LOW_S,LOW_T, CAP_F, LOW_I, LOW_R, LOW_S, LOW_T, COLON};
65
66 // earliestFirst:
67 static const UChar gEarlierFirstPrefix[] = {LOW_E, LOW_A, LOW_R, LOW_L, LOW_I, LOW_E, LOW_S, LOW_T, CAP_F, LOW_I, LOW_R, LOW_S, LOW_T, COLON};
68
69
70 class FormattedDateIntervalData : public FormattedValueFieldPositionIteratorImpl {
71 public:
FormattedDateIntervalData(UErrorCode & status)72 FormattedDateIntervalData(UErrorCode& status) : FormattedValueFieldPositionIteratorImpl(5, status) {}
73 virtual ~FormattedDateIntervalData();
74 };
75
76 FormattedDateIntervalData::~FormattedDateIntervalData() = default;
77
78 UPRV_FORMATTED_VALUE_SUBCLASS_AUTO_IMPL(FormattedDateInterval)
79
80
81 UOBJECT_DEFINE_RTTI_IMPLEMENTATION(DateIntervalFormat)
82
83 // Mutex, protects access to fDateFormat, fFromCalendar and fToCalendar.
84 // Needed because these data members are modified by const methods of DateIntervalFormat.
85
86 static UMutex gFormatterMutex;
87
88 DateIntervalFormat* U_EXPORT2
createInstance(const UnicodeString & skeleton,UErrorCode & status)89 DateIntervalFormat::createInstance(const UnicodeString& skeleton,
90 UErrorCode& status) {
91 return createInstance(skeleton, Locale::getDefault(), status);
92 }
93
94
95 DateIntervalFormat* U_EXPORT2
createInstance(const UnicodeString & skeleton,const Locale & locale,UErrorCode & status)96 DateIntervalFormat::createInstance(const UnicodeString& skeleton,
97 const Locale& locale,
98 UErrorCode& status) {
99 #ifdef DTITVFMT_DEBUG
100 char result[1000];
101 char result_1[1000];
102 char mesg[2000];
103 skeleton.extract(0, skeleton.length(), result, "UTF-8");
104 UnicodeString pat;
105 ((SimpleDateFormat*)dtfmt)->toPattern(pat);
106 pat.extract(0, pat.length(), result_1, "UTF-8");
107 sprintf(mesg, "skeleton: %s; pattern: %s\n", result, result_1);
108 PRINTMESG(mesg)
109 #endif
110
111 DateIntervalInfo* dtitvinf = new DateIntervalInfo(locale, status);
112 if (dtitvinf == nullptr) {
113 status = U_MEMORY_ALLOCATION_ERROR;
114 return nullptr;
115 }
116 return create(locale, dtitvinf, &skeleton, status);
117 }
118
119
120
121 DateIntervalFormat* U_EXPORT2
createInstance(const UnicodeString & skeleton,const DateIntervalInfo & dtitvinf,UErrorCode & status)122 DateIntervalFormat::createInstance(const UnicodeString& skeleton,
123 const DateIntervalInfo& dtitvinf,
124 UErrorCode& status) {
125 return createInstance(skeleton, Locale::getDefault(), dtitvinf, status);
126 }
127
128
129 DateIntervalFormat* U_EXPORT2
createInstance(const UnicodeString & skeleton,const Locale & locale,const DateIntervalInfo & dtitvinf,UErrorCode & status)130 DateIntervalFormat::createInstance(const UnicodeString& skeleton,
131 const Locale& locale,
132 const DateIntervalInfo& dtitvinf,
133 UErrorCode& status) {
134 DateIntervalInfo* ptn = dtitvinf.clone();
135 return create(locale, ptn, &skeleton, status);
136 }
137
138
DateIntervalFormat()139 DateIntervalFormat::DateIntervalFormat()
140 : fInfo(nullptr),
141 fDateFormat(nullptr),
142 fFromCalendar(nullptr),
143 fToCalendar(nullptr),
144 fLocale(Locale::getRoot()),
145 fDatePattern(nullptr),
146 fTimePattern(nullptr),
147 fDateTimeFormat(nullptr),
148 fCapitalizationContext(UDISPCTX_CAPITALIZATION_NONE)
149 {}
150
151
DateIntervalFormat(const DateIntervalFormat & itvfmt)152 DateIntervalFormat::DateIntervalFormat(const DateIntervalFormat& itvfmt)
153 : Format(itvfmt),
154 fInfo(nullptr),
155 fDateFormat(nullptr),
156 fFromCalendar(nullptr),
157 fToCalendar(nullptr),
158 fLocale(itvfmt.fLocale),
159 fDatePattern(nullptr),
160 fTimePattern(nullptr),
161 fDateTimeFormat(nullptr),
162 fCapitalizationContext(UDISPCTX_CAPITALIZATION_NONE) {
163 *this = itvfmt;
164 }
165
166
167 DateIntervalFormat&
operator =(const DateIntervalFormat & itvfmt)168 DateIntervalFormat::operator=(const DateIntervalFormat& itvfmt) {
169 if ( this != &itvfmt ) {
170 delete fDateFormat;
171 delete fInfo;
172 delete fFromCalendar;
173 delete fToCalendar;
174 delete fDatePattern;
175 delete fTimePattern;
176 delete fDateTimeFormat;
177 {
178 Mutex lock(&gFormatterMutex);
179 if ( itvfmt.fDateFormat ) {
180 fDateFormat = itvfmt.fDateFormat->clone();
181 } else {
182 fDateFormat = nullptr;
183 }
184 if ( itvfmt.fFromCalendar ) {
185 fFromCalendar = itvfmt.fFromCalendar->clone();
186 } else {
187 fFromCalendar = nullptr;
188 }
189 if ( itvfmt.fToCalendar ) {
190 fToCalendar = itvfmt.fToCalendar->clone();
191 } else {
192 fToCalendar = nullptr;
193 }
194 }
195 if ( itvfmt.fInfo ) {
196 fInfo = itvfmt.fInfo->clone();
197 } else {
198 fInfo = nullptr;
199 }
200 fSkeleton = itvfmt.fSkeleton;
201 int8_t i;
202 for ( i = 0; i< DateIntervalInfo::kIPI_MAX_INDEX; ++i ) {
203 fIntervalPatterns[i] = itvfmt.fIntervalPatterns[i];
204 }
205 fLocale = itvfmt.fLocale;
206 fDatePattern = (itvfmt.fDatePattern)? itvfmt.fDatePattern->clone(): nullptr;
207 fTimePattern = (itvfmt.fTimePattern)? itvfmt.fTimePattern->clone(): nullptr;
208 fDateTimeFormat = (itvfmt.fDateTimeFormat)? itvfmt.fDateTimeFormat->clone(): nullptr;
209 fCapitalizationContext = itvfmt.fCapitalizationContext;
210 }
211 return *this;
212 }
213
214
~DateIntervalFormat()215 DateIntervalFormat::~DateIntervalFormat() {
216 delete fInfo;
217 delete fDateFormat;
218 delete fFromCalendar;
219 delete fToCalendar;
220 delete fDatePattern;
221 delete fTimePattern;
222 delete fDateTimeFormat;
223 }
224
225
226 DateIntervalFormat*
clone() const227 DateIntervalFormat::clone() const {
228 return new DateIntervalFormat(*this);
229 }
230
231
232 UBool
operator ==(const Format & other) const233 DateIntervalFormat::operator==(const Format& other) const {
234 if (typeid(*this) != typeid(other)) {return FALSE;}
235 const DateIntervalFormat* fmt = (DateIntervalFormat*)&other;
236 if (this == fmt) {return TRUE;}
237 if (!Format::operator==(other)) {return FALSE;}
238 if ((fInfo != fmt->fInfo) && (fInfo == nullptr || fmt->fInfo == nullptr)) {return FALSE;}
239 if (fInfo && fmt->fInfo && (*fInfo != *fmt->fInfo )) {return FALSE;}
240 {
241 Mutex lock(&gFormatterMutex);
242 if (fDateFormat != fmt->fDateFormat && (fDateFormat == nullptr || fmt->fDateFormat == nullptr)) {return FALSE;}
243 if (fDateFormat && fmt->fDateFormat && (*fDateFormat != *fmt->fDateFormat)) {return FALSE;}
244 }
245 // note: fFromCalendar and fToCalendar hold no persistent state, and therefore do not participate in operator ==.
246 // fDateFormat has the primary calendar for the DateIntervalFormat.
247 if (fSkeleton != fmt->fSkeleton) {return FALSE;}
248 if (fDatePattern != fmt->fDatePattern && (fDatePattern == nullptr || fmt->fDatePattern == nullptr)) {return FALSE;}
249 if (fDatePattern && fmt->fDatePattern && (*fDatePattern != *fmt->fDatePattern)) {return FALSE;}
250 if (fTimePattern != fmt->fTimePattern && (fTimePattern == nullptr || fmt->fTimePattern == nullptr)) {return FALSE;}
251 if (fTimePattern && fmt->fTimePattern && (*fTimePattern != *fmt->fTimePattern)) {return FALSE;}
252 if (fDateTimeFormat != fmt->fDateTimeFormat && (fDateTimeFormat == nullptr || fmt->fDateTimeFormat == nullptr)) {return FALSE;}
253 if (fDateTimeFormat && fmt->fDateTimeFormat && (*fDateTimeFormat != *fmt->fDateTimeFormat)) {return FALSE;}
254 if (fLocale != fmt->fLocale) {return FALSE;}
255
256 for (int32_t i = 0; i< DateIntervalInfo::kIPI_MAX_INDEX; ++i ) {
257 if (fIntervalPatterns[i].firstPart != fmt->fIntervalPatterns[i].firstPart) {return FALSE;}
258 if (fIntervalPatterns[i].secondPart != fmt->fIntervalPatterns[i].secondPart ) {return FALSE;}
259 if (fIntervalPatterns[i].laterDateFirst != fmt->fIntervalPatterns[i].laterDateFirst) {return FALSE;}
260 }
261 if (fCapitalizationContext != fmt->fCapitalizationContext) {return FALSE;}
262 return TRUE;
263 }
264
265
266 UnicodeString&
format(const Formattable & obj,UnicodeString & appendTo,FieldPosition & fieldPosition,UErrorCode & status) const267 DateIntervalFormat::format(const Formattable& obj,
268 UnicodeString& appendTo,
269 FieldPosition& fieldPosition,
270 UErrorCode& status) const {
271 if ( U_FAILURE(status) ) {
272 return appendTo;
273 }
274
275 if ( obj.getType() == Formattable::kObject ) {
276 const UObject* formatObj = obj.getObject();
277 const DateInterval* interval = dynamic_cast<const DateInterval*>(formatObj);
278 if (interval != nullptr) {
279 return format(interval, appendTo, fieldPosition, status);
280 }
281 }
282 status = U_ILLEGAL_ARGUMENT_ERROR;
283 return appendTo;
284 }
285
286
287 UnicodeString&
format(const DateInterval * dtInterval,UnicodeString & appendTo,FieldPosition & fieldPosition,UErrorCode & status) const288 DateIntervalFormat::format(const DateInterval* dtInterval,
289 UnicodeString& appendTo,
290 FieldPosition& fieldPosition,
291 UErrorCode& status) const {
292 if ( U_FAILURE(status) ) {
293 return appendTo;
294 }
295 if (fDateFormat == nullptr || fInfo == nullptr) {
296 status = U_INVALID_STATE_ERROR;
297 return appendTo;
298 }
299
300 FieldPositionOnlyHandler handler(fieldPosition);
301 handler.setAcceptFirstOnly(TRUE);
302 int8_t ignore;
303
304 Mutex lock(&gFormatterMutex);
305 return formatIntervalImpl(*dtInterval, appendTo, ignore, handler, status);
306 }
307
308
formatToValue(const DateInterval & dtInterval,UErrorCode & status) const309 FormattedDateInterval DateIntervalFormat::formatToValue(
310 const DateInterval& dtInterval,
311 UErrorCode& status) const {
312 if (U_FAILURE(status)) {
313 return FormattedDateInterval(status);
314 }
315 // LocalPointer only sets OOM status if U_SUCCESS is true.
316 LocalPointer<FormattedDateIntervalData> result(new FormattedDateIntervalData(status), status);
317 if (U_FAILURE(status)) {
318 return FormattedDateInterval(status);
319 }
320 UnicodeString string;
321 int8_t firstIndex;
322 auto handler = result->getHandler(status);
323 handler.setCategory(UFIELD_CATEGORY_DATE);
324 {
325 Mutex lock(&gFormatterMutex);
326 formatIntervalImpl(dtInterval, string, firstIndex, handler, status);
327 }
328 handler.getError(status);
329 result->appendString(string, status);
330 if (U_FAILURE(status)) {
331 return FormattedDateInterval(status);
332 }
333
334 // Compute the span fields and sort them into place:
335 if (firstIndex != -1) {
336 result->addOverlapSpans(UFIELD_CATEGORY_DATE_INTERVAL_SPAN, firstIndex, status);
337 if (U_FAILURE(status)) {
338 return FormattedDateInterval(status);
339 }
340 result->sort();
341 }
342
343 return FormattedDateInterval(result.orphan());
344 }
345
346
347 UnicodeString&
format(Calendar & fromCalendar,Calendar & toCalendar,UnicodeString & appendTo,FieldPosition & pos,UErrorCode & status) const348 DateIntervalFormat::format(Calendar& fromCalendar,
349 Calendar& toCalendar,
350 UnicodeString& appendTo,
351 FieldPosition& pos,
352 UErrorCode& status) const {
353 FieldPositionOnlyHandler handler(pos);
354 handler.setAcceptFirstOnly(TRUE);
355 int8_t ignore;
356
357 Mutex lock(&gFormatterMutex);
358 return formatImpl(fromCalendar, toCalendar, appendTo, ignore, handler, status);
359 }
360
361
formatToValue(Calendar & fromCalendar,Calendar & toCalendar,UErrorCode & status) const362 FormattedDateInterval DateIntervalFormat::formatToValue(
363 Calendar& fromCalendar,
364 Calendar& toCalendar,
365 UErrorCode& status) const {
366 if (U_FAILURE(status)) {
367 return FormattedDateInterval(status);
368 }
369 // LocalPointer only sets OOM status if U_SUCCESS is true.
370 LocalPointer<FormattedDateIntervalData> result(new FormattedDateIntervalData(status), status);
371 if (U_FAILURE(status)) {
372 return FormattedDateInterval(status);
373 }
374 UnicodeString string;
375 int8_t firstIndex;
376 auto handler = result->getHandler(status);
377 handler.setCategory(UFIELD_CATEGORY_DATE);
378 {
379 Mutex lock(&gFormatterMutex);
380 formatImpl(fromCalendar, toCalendar, string, firstIndex, handler, status);
381 }
382 handler.getError(status);
383 result->appendString(string, status);
384 if (U_FAILURE(status)) {
385 return FormattedDateInterval(status);
386 }
387
388 // Compute the span fields and sort them into place:
389 if (firstIndex != -1) {
390 result->addOverlapSpans(UFIELD_CATEGORY_DATE_INTERVAL_SPAN, firstIndex, status);
391 result->sort();
392 }
393
394 return FormattedDateInterval(result.orphan());
395 }
396
397
formatIntervalImpl(const DateInterval & dtInterval,UnicodeString & appendTo,int8_t & firstIndex,FieldPositionHandler & fphandler,UErrorCode & status) const398 UnicodeString& DateIntervalFormat::formatIntervalImpl(
399 const DateInterval& dtInterval,
400 UnicodeString& appendTo,
401 int8_t& firstIndex,
402 FieldPositionHandler& fphandler,
403 UErrorCode& status) const {
404 if (U_FAILURE(status)) {
405 return appendTo;
406 }
407 if (fFromCalendar == nullptr || fToCalendar == nullptr) {
408 status = U_INVALID_STATE_ERROR;
409 return appendTo;
410 }
411 fFromCalendar->setTime(dtInterval.getFromDate(), status);
412 fToCalendar->setTime(dtInterval.getToDate(), status);
413 return formatImpl(*fFromCalendar, *fToCalendar, appendTo, firstIndex, fphandler, status);
414 }
415
416
417 // The following is only called from within the gFormatterMutex lock
418 UnicodeString&
formatImpl(Calendar & fromCalendar,Calendar & toCalendar,UnicodeString & appendTo,int8_t & firstIndex,FieldPositionHandler & fphandler,UErrorCode & status) const419 DateIntervalFormat::formatImpl(Calendar& fromCalendar,
420 Calendar& toCalendar,
421 UnicodeString& appendTo,
422 int8_t& firstIndex,
423 FieldPositionHandler& fphandler,
424 UErrorCode& status) const {
425 if ( U_FAILURE(status) ) {
426 return appendTo;
427 }
428
429 // Initialize firstIndex to -1 (single date, no range)
430 firstIndex = -1;
431
432 // not support different calendar types and time zones
433 //if ( fromCalendar.getType() != toCalendar.getType() ) {
434 if ( !fromCalendar.isEquivalentTo(toCalendar) ) {
435 status = U_ILLEGAL_ARGUMENT_ERROR;
436 return appendTo;
437 }
438
439 // First, find the largest different calendar field.
440 UCalendarDateFields field = UCAL_FIELD_COUNT;
441
442 if ( fromCalendar.get(UCAL_ERA,status) != toCalendar.get(UCAL_ERA,status)) {
443 field = UCAL_ERA;
444 } else if ( fromCalendar.get(UCAL_YEAR, status) !=
445 toCalendar.get(UCAL_YEAR, status) ) {
446 field = UCAL_YEAR;
447 } else if ( fromCalendar.get(UCAL_MONTH, status) !=
448 toCalendar.get(UCAL_MONTH, status) ) {
449 field = UCAL_MONTH;
450 } else if ( fromCalendar.get(UCAL_DATE, status) !=
451 toCalendar.get(UCAL_DATE, status) ) {
452 field = UCAL_DATE;
453 } else if ( fromCalendar.get(UCAL_AM_PM, status) !=
454 toCalendar.get(UCAL_AM_PM, status) ) {
455 field = UCAL_AM_PM;
456 } else if ( fromCalendar.get(UCAL_HOUR, status) !=
457 toCalendar.get(UCAL_HOUR, status) ) {
458 field = UCAL_HOUR;
459 } else if ( fromCalendar.get(UCAL_MINUTE, status) !=
460 toCalendar.get(UCAL_MINUTE, status) ) {
461 field = UCAL_MINUTE;
462 } else if ( fromCalendar.get(UCAL_SECOND, status) !=
463 toCalendar.get(UCAL_SECOND, status) ) {
464 field = UCAL_SECOND;
465 } else if ( fromCalendar.get(UCAL_MILLISECOND, status) !=
466 toCalendar.get(UCAL_MILLISECOND, status) ) {
467 field = UCAL_MILLISECOND;
468 }
469
470 if ( U_FAILURE(status) ) {
471 return appendTo;
472 }
473 UErrorCode tempStatus = U_ZERO_ERROR; // for setContext, ignored
474 // Set up fDateFormat to handle the first or only part of the interval
475 // (override later for any second part). Inside lock, OK to modify fDateFormat.
476 fDateFormat->setContext(fCapitalizationContext, tempStatus);
477
478 if ( field == UCAL_FIELD_COUNT ) {
479 /* ignore the millisecond etc. small fields' difference.
480 * use single date when all the above are the same.
481 */
482 return fDateFormat->_format(fromCalendar, appendTo, fphandler, status);
483 }
484 UBool fromToOnSameDay = (field==UCAL_AM_PM || field==UCAL_HOUR || field==UCAL_MINUTE || field==UCAL_SECOND || field==UCAL_MILLISECOND);
485
486 // following call should not set wrong status,
487 // all the pass-in fields are valid till here
488 int32_t itvPtnIndex = DateIntervalInfo::calendarFieldToIntervalIndex(field,
489 status);
490 const PatternInfo& intervalPattern = fIntervalPatterns[itvPtnIndex];
491
492 if ( intervalPattern.firstPart.isEmpty() &&
493 intervalPattern.secondPart.isEmpty() ) {
494 if ( fDateFormat->isFieldUnitIgnored(field) ) {
495 /* the largest different calendar field is small than
496 * the smallest calendar field in pattern,
497 * return single date format.
498 */
499 return fDateFormat->_format(fromCalendar, appendTo, fphandler, status);
500 }
501 return fallbackFormat(fromCalendar, toCalendar, fromToOnSameDay, appendTo, firstIndex, fphandler, status);
502 }
503 // If the first part in interval pattern is empty,
504 // the 2nd part of it saves the full-pattern used in fall-back.
505 // For a 'real' interval pattern, the first part will never be empty.
506 if ( intervalPattern.firstPart.isEmpty() ) {
507 // fall back
508 UnicodeString originalPattern;
509 fDateFormat->toPattern(originalPattern);
510 fDateFormat->applyPattern(intervalPattern.secondPart);
511 appendTo = fallbackFormat(fromCalendar, toCalendar, fromToOnSameDay, appendTo, firstIndex, fphandler, status);
512 fDateFormat->applyPattern(originalPattern);
513 return appendTo;
514 }
515 Calendar* firstCal;
516 Calendar* secondCal;
517 if ( intervalPattern.laterDateFirst ) {
518 firstCal = &toCalendar;
519 secondCal = &fromCalendar;
520 firstIndex = 1;
521 } else {
522 firstCal = &fromCalendar;
523 secondCal = &toCalendar;
524 firstIndex = 0;
525 }
526 // break the interval pattern into 2 parts,
527 // first part should not be empty,
528 UnicodeString originalPattern;
529 fDateFormat->toPattern(originalPattern);
530 fDateFormat->applyPattern(intervalPattern.firstPart);
531 fDateFormat->_format(*firstCal, appendTo, fphandler, status);
532
533 if ( !intervalPattern.secondPart.isEmpty() ) {
534 fDateFormat->applyPattern(intervalPattern.secondPart);
535 // No capitalization for second part of interval
536 tempStatus = U_ZERO_ERROR;
537 fDateFormat->setContext(UDISPCTX_CAPITALIZATION_NONE, tempStatus);
538 fDateFormat->_format(*secondCal, appendTo, fphandler, status);
539 }
540 fDateFormat->applyPattern(originalPattern);
541 return appendTo;
542 }
543
544
545
546 void
parseObject(const UnicodeString &,Formattable &,ParsePosition &) const547 DateIntervalFormat::parseObject(const UnicodeString& /* source */,
548 Formattable& /* result */,
549 ParsePosition& /* parse_pos */) const {
550 // parseObject(const UnicodeString&, Formattable&, UErrorCode&) const
551 // will set status as U_INVALID_FORMAT_ERROR if
552 // parse_pos is still 0
553 }
554
555
556
557
558 const DateIntervalInfo*
getDateIntervalInfo() const559 DateIntervalFormat::getDateIntervalInfo() const {
560 return fInfo;
561 }
562
563
564 void
setDateIntervalInfo(const DateIntervalInfo & newItvPattern,UErrorCode & status)565 DateIntervalFormat::setDateIntervalInfo(const DateIntervalInfo& newItvPattern,
566 UErrorCode& status) {
567 delete fInfo;
568 fInfo = new DateIntervalInfo(newItvPattern);
569 if (fInfo == nullptr) {
570 status = U_MEMORY_ALLOCATION_ERROR;
571 }
572
573 // Delete patterns that get reset by initializePattern
574 delete fDatePattern;
575 fDatePattern = nullptr;
576 delete fTimePattern;
577 fTimePattern = nullptr;
578 delete fDateTimeFormat;
579 fDateTimeFormat = nullptr;
580
581 if (fDateFormat) {
582 initializePattern(status);
583 }
584 }
585
586
587
588 const DateFormat*
getDateFormat() const589 DateIntervalFormat::getDateFormat() const {
590 return fDateFormat;
591 }
592
593
594 void
adoptTimeZone(TimeZone * zone)595 DateIntervalFormat::adoptTimeZone(TimeZone* zone)
596 {
597 if (fDateFormat != nullptr) {
598 fDateFormat->adoptTimeZone(zone);
599 }
600 // The fDateFormat has the primary calendar for the DateIntervalFormat and has
601 // ownership of any adopted TimeZone; fFromCalendar and fToCalendar are internal
602 // work clones of that calendar (and should not also be given ownership of the
603 // adopted TimeZone).
604 if (fFromCalendar) {
605 fFromCalendar->setTimeZone(*zone);
606 }
607 if (fToCalendar) {
608 fToCalendar->setTimeZone(*zone);
609 }
610 }
611
612 void
setTimeZone(const TimeZone & zone)613 DateIntervalFormat::setTimeZone(const TimeZone& zone)
614 {
615 if (fDateFormat != nullptr) {
616 fDateFormat->setTimeZone(zone);
617 }
618 // The fDateFormat has the primary calendar for the DateIntervalFormat;
619 // fFromCalendar and fToCalendar are internal work clones of that calendar.
620 if (fFromCalendar) {
621 fFromCalendar->setTimeZone(zone);
622 }
623 if (fToCalendar) {
624 fToCalendar->setTimeZone(zone);
625 }
626 }
627
628 const TimeZone&
getTimeZone() const629 DateIntervalFormat::getTimeZone() const
630 {
631 if (fDateFormat != nullptr) {
632 Mutex lock(&gFormatterMutex);
633 return fDateFormat->getTimeZone();
634 }
635 // If fDateFormat is nullptr (unexpected), create default timezone.
636 return *(TimeZone::createDefault());
637 }
638
639 void
setContext(UDisplayContext value,UErrorCode & status)640 DateIntervalFormat::setContext(UDisplayContext value, UErrorCode& status)
641 {
642 if (U_FAILURE(status))
643 return;
644 if ( (UDisplayContextType)((uint32_t)value >> 8) == UDISPCTX_TYPE_CAPITALIZATION ) {
645 fCapitalizationContext = value;
646 } else {
647 status = U_ILLEGAL_ARGUMENT_ERROR;
648 }
649 }
650
651 UDisplayContext
getContext(UDisplayContextType type,UErrorCode & status) const652 DateIntervalFormat::getContext(UDisplayContextType type, UErrorCode& status) const
653 {
654 if (U_FAILURE(status))
655 return (UDisplayContext)0;
656 if (type != UDISPCTX_TYPE_CAPITALIZATION) {
657 status = U_ILLEGAL_ARGUMENT_ERROR;
658 return (UDisplayContext)0;
659 }
660 return fCapitalizationContext;
661 }
662
DateIntervalFormat(const Locale & locale,DateIntervalInfo * dtItvInfo,const UnicodeString * skeleton,UErrorCode & status)663 DateIntervalFormat::DateIntervalFormat(const Locale& locale,
664 DateIntervalInfo* dtItvInfo,
665 const UnicodeString* skeleton,
666 UErrorCode& status)
667 : fInfo(nullptr),
668 fDateFormat(nullptr),
669 fFromCalendar(nullptr),
670 fToCalendar(nullptr),
671 fLocale(locale),
672 fDatePattern(nullptr),
673 fTimePattern(nullptr),
674 fDateTimeFormat(nullptr),
675 fCapitalizationContext(UDISPCTX_CAPITALIZATION_NONE)
676 {
677 LocalPointer<DateIntervalInfo> info(dtItvInfo, status);
678 LocalPointer<SimpleDateFormat> dtfmt(static_cast<SimpleDateFormat *>(
679 DateFormat::createInstanceForSkeleton(*skeleton, locale, status)), status);
680 if (U_FAILURE(status)) {
681 return;
682 }
683
684 if ( skeleton ) {
685 fSkeleton = *skeleton;
686 }
687 fInfo = info.orphan();
688 fDateFormat = dtfmt.orphan();
689 if ( fDateFormat->getCalendar() ) {
690 fFromCalendar = fDateFormat->getCalendar()->clone();
691 fToCalendar = fDateFormat->getCalendar()->clone();
692 }
693 initializePattern(status);
694 }
695
696 DateIntervalFormat* U_EXPORT2
create(const Locale & locale,DateIntervalInfo * dtitvinf,const UnicodeString * skeleton,UErrorCode & status)697 DateIntervalFormat::create(const Locale& locale,
698 DateIntervalInfo* dtitvinf,
699 const UnicodeString* skeleton,
700 UErrorCode& status) {
701 DateIntervalFormat* f = new DateIntervalFormat(locale, dtitvinf,
702 skeleton, status);
703 if ( f == nullptr ) {
704 status = U_MEMORY_ALLOCATION_ERROR;
705 delete dtitvinf;
706 } else if ( U_FAILURE(status) ) {
707 // safe to delete f, although nothing actually is saved
708 delete f;
709 f = 0;
710 }
711 return f;
712 }
713
714
715
716 /**
717 * Initialize interval patterns locale to this formatter
718 *
719 * This code is a bit complicated since
720 * 1. the interval patterns saved in resource bundle files are interval
721 * patterns based on date or time only.
722 * It does not have interval patterns based on both date and time.
723 * Interval patterns on both date and time are algorithm generated.
724 *
725 * For example, it has interval patterns on skeleton "dMy" and "hm",
726 * but it does not have interval patterns on skeleton "dMyhm".
727 *
728 * The rule to genearte interval patterns for both date and time skeleton are
729 * 1) when the year, month, or day differs, concatenate the two original
730 * expressions with a separator between,
731 * For example, interval pattern from "Jan 10, 2007 10:10 am"
732 * to "Jan 11, 2007 10:10am" is
733 * "Jan 10, 2007 10:10 am - Jan 11, 2007 10:10am"
734 *
735 * 2) otherwise, present the date followed by the range expression
736 * for the time.
737 * For example, interval pattern from "Jan 10, 2007 10:10 am"
738 * to "Jan 10, 2007 11:10am" is
739 * "Jan 10, 2007 10:10 am - 11:10am"
740 *
741 * 2. even a pattern does not request a certion calendar field,
742 * the interval pattern needs to include such field if such fields are
743 * different between 2 dates.
744 * For example, a pattern/skeleton is "hm", but the interval pattern
745 * includes year, month, and date when year, month, and date differs.
746 *
747 * @param status output param set to success/failure code on exit
748 * @stable ICU 4.0
749 */
750 void
initializePattern(UErrorCode & status)751 DateIntervalFormat::initializePattern(UErrorCode& status) {
752 if ( U_FAILURE(status) ) {
753 return;
754 }
755 const Locale& locale = fDateFormat->getSmpFmtLocale();
756 if ( fSkeleton.isEmpty() ) {
757 UnicodeString fullPattern;
758 fDateFormat->toPattern(fullPattern);
759 #ifdef DTITVFMT_DEBUG
760 char result[1000];
761 char result_1[1000];
762 char mesg[2000];
763 fSkeleton.extract(0, fSkeleton.length(), result, "UTF-8");
764 sprintf(mesg, "in getBestSkeleton: fSkeleton: %s; \n", result);
765 PRINTMESG(mesg)
766 #endif
767 // fSkeleton is already set by createDateIntervalInstance()
768 // or by createInstance(UnicodeString skeleton, .... )
769 fSkeleton = DateTimePatternGenerator::staticGetSkeleton(
770 fullPattern, status);
771 if ( U_FAILURE(status) ) {
772 return;
773 }
774 }
775
776 // initialize the fIntervalPattern ordering
777 int8_t i;
778 for ( i = 0; i < DateIntervalInfo::kIPI_MAX_INDEX; ++i ) {
779 fIntervalPatterns[i].laterDateFirst = fInfo->getDefaultOrder();
780 }
781
782 /* Check whether the skeleton is a combination of date and time.
783 * For the complication reason 1 explained above.
784 */
785 UnicodeString dateSkeleton;
786 UnicodeString timeSkeleton;
787 UnicodeString normalizedTimeSkeleton;
788 UnicodeString normalizedDateSkeleton;
789
790
791 /* the difference between time skeleton and normalizedTimeSkeleton are:
792 * 1. (Formerly, normalized time skeleton folded 'H' to 'h'; no longer true)
793 * 2. (Formerly, 'a' was omitted in normalized time skeleton; this is now handled elsewhere)
794 * 3. there is only one appearance for 'h' or 'H', 'm','v', 'z' in normalized
795 * time skeleton
796 *
797 * The difference between date skeleton and normalizedDateSkeleton are:
798 * 1. both 'y' and 'd' appear only once in normalizeDateSkeleton
799 * 2. 'E' and 'EE' are normalized into 'EEE'
800 * 3. 'MM' is normalized into 'M'
801 */
802 UnicodeString convertedSkeleton = normalizeHourMetacharacters(fSkeleton);
803 getDateTimeSkeleton(convertedSkeleton, dateSkeleton, normalizedDateSkeleton,
804 timeSkeleton, normalizedTimeSkeleton);
805
806 #ifdef DTITVFMT_DEBUG
807 char result[1000];
808 char result_1[1000];
809 char mesg[2000];
810 fSkeleton.extract(0, fSkeleton.length(), result, "UTF-8");
811 sprintf(mesg, "in getBestSkeleton: fSkeleton: %s; \n", result);
812 PRINTMESG(mesg)
813 #endif
814
815 // move this up here since we need it for fallbacks
816 if ( timeSkeleton.length() > 0 && dateSkeleton.length() > 0 ) {
817 // Need the Date/Time pattern for concatenation of the date
818 // with the time interval.
819 // The date/time pattern ( such as {0} {1} ) is saved in
820 // calendar, that is why need to get the CalendarData here.
821 LocalUResourceBundlePointer dateTimePatternsRes(ures_open(nullptr, locale.getBaseName(), &status));
822 ures_getByKey(dateTimePatternsRes.getAlias(), gCalendarTag,
823 dateTimePatternsRes.getAlias(), &status);
824 ures_getByKeyWithFallback(dateTimePatternsRes.getAlias(), gGregorianTag,
825 dateTimePatternsRes.getAlias(), &status);
826 ures_getByKeyWithFallback(dateTimePatternsRes.getAlias(), gDateTimePatternsTag,
827 dateTimePatternsRes.getAlias(), &status);
828
829 int32_t dateTimeFormatLength;
830 const UChar* dateTimeFormat = ures_getStringByIndex(
831 dateTimePatternsRes.getAlias(),
832 (int32_t)DateFormat::kDateTime,
833 &dateTimeFormatLength, &status);
834 if ( U_SUCCESS(status) && dateTimeFormatLength >= 3 ) {
835 fDateTimeFormat = new UnicodeString(dateTimeFormat, dateTimeFormatLength);
836 if (fDateTimeFormat == nullptr) {
837 status = U_MEMORY_ALLOCATION_ERROR;
838 return;
839 }
840 }
841 }
842
843 UBool found = setSeparateDateTimePtn(normalizedDateSkeleton,
844 normalizedTimeSkeleton);
845
846 // for skeletons with seconds, found is false and we enter this block
847 if ( found == false ) {
848 // use fallback
849 // TODO: if user asks "m"(minute), but "d"(day) differ
850 if ( timeSkeleton.length() != 0 ) {
851 if ( dateSkeleton.length() == 0 ) {
852 // prefix with yMd
853 timeSkeleton.insert(0, gDateFormatSkeleton[DateFormat::kShort], -1);
854 UnicodeString pattern = DateFormat::getBestPattern(
855 locale, timeSkeleton, status);
856 if ( U_FAILURE(status) ) {
857 return;
858 }
859 // for fall back interval patterns,
860 // the first part of the pattern is empty,
861 // the second part of the pattern is the full-pattern
862 // should be used in fall-back.
863 setPatternInfo(UCAL_DATE, nullptr, &pattern, fInfo->getDefaultOrder());
864 setPatternInfo(UCAL_MONTH, nullptr, &pattern, fInfo->getDefaultOrder());
865 setPatternInfo(UCAL_YEAR, nullptr, &pattern, fInfo->getDefaultOrder());
866
867 timeSkeleton.insert(0, CAP_G);
868 pattern = DateFormat::getBestPattern(
869 locale, timeSkeleton, status);
870 if ( U_FAILURE(status) ) {
871 return;
872 }
873 setPatternInfo(UCAL_ERA, nullptr, &pattern, fInfo->getDefaultOrder());
874 } else {
875 // TODO: fall back
876 }
877 } else {
878 // TODO: fall back
879 }
880 return;
881 } // end of skeleton not found
882 // interval patterns for skeleton are found in resource
883 if ( timeSkeleton.length() == 0 ) {
884 // done
885 } else if ( dateSkeleton.length() == 0 ) {
886 // prefix with yMd
887 timeSkeleton.insert(0, gDateFormatSkeleton[DateFormat::kShort], -1);
888 UnicodeString pattern = DateFormat::getBestPattern(
889 locale, timeSkeleton, status);
890 if ( U_FAILURE(status) ) {
891 return;
892 }
893 // for fall back interval patterns,
894 // the first part of the pattern is empty,
895 // the second part of the pattern is the full-pattern
896 // should be used in fall-back.
897 setPatternInfo(UCAL_DATE, nullptr, &pattern, fInfo->getDefaultOrder());
898 setPatternInfo(UCAL_MONTH, nullptr, &pattern, fInfo->getDefaultOrder());
899 setPatternInfo(UCAL_YEAR, nullptr, &pattern, fInfo->getDefaultOrder());
900
901 timeSkeleton.insert(0, CAP_G);
902 pattern = DateFormat::getBestPattern(
903 locale, timeSkeleton, status);
904 if ( U_FAILURE(status) ) {
905 return;
906 }
907 setPatternInfo(UCAL_ERA, nullptr, &pattern, fInfo->getDefaultOrder());
908 } else {
909 /* if both present,
910 * 1) when the era, year, month, or day differs,
911 * concatenate the two original expressions with a separator between,
912 * 2) otherwise, present the date followed by the
913 * range expression for the time.
914 */
915 /*
916 * 1) when the era, year, month, or day differs,
917 * concatenate the two original expressions with a separator between,
918 */
919 // if field exists, use fall back
920 UnicodeString skeleton = fSkeleton;
921 if ( !fieldExistsInSkeleton(UCAL_DATE, dateSkeleton) ) {
922 // prefix skeleton with 'd'
923 skeleton.insert(0, LOW_D);
924 setFallbackPattern(UCAL_DATE, skeleton, status);
925 }
926 if ( !fieldExistsInSkeleton(UCAL_MONTH, dateSkeleton) ) {
927 // then prefix skeleton with 'M'
928 skeleton.insert(0, CAP_M);
929 setFallbackPattern(UCAL_MONTH, skeleton, status);
930 }
931 if ( !fieldExistsInSkeleton(UCAL_YEAR, dateSkeleton) ) {
932 // then prefix skeleton with 'y'
933 skeleton.insert(0, LOW_Y);
934 setFallbackPattern(UCAL_YEAR, skeleton, status);
935 }
936 if ( !fieldExistsInSkeleton(UCAL_ERA, dateSkeleton) ) {
937 // then prefix skeleton with 'G'
938 skeleton.insert(0, CAP_G);
939 setFallbackPattern(UCAL_ERA, skeleton, status);
940 }
941
942 /*
943 * 2) otherwise, present the date followed by the
944 * range expression for the time.
945 */
946
947 if ( fDateTimeFormat == nullptr ) {
948 // earlier failure getting dateTimeFormat
949 return;
950 }
951
952 UnicodeString datePattern = DateFormat::getBestPattern(
953 locale, dateSkeleton, status);
954
955 concatSingleDate2TimeInterval(*fDateTimeFormat, datePattern, UCAL_AM_PM, status);
956 concatSingleDate2TimeInterval(*fDateTimeFormat, datePattern, UCAL_HOUR, status);
957 concatSingleDate2TimeInterval(*fDateTimeFormat, datePattern, UCAL_MINUTE, status);
958 }
959 }
960
961
962
963 UnicodeString
normalizeHourMetacharacters(const UnicodeString & skeleton) const964 DateIntervalFormat::normalizeHourMetacharacters(const UnicodeString& skeleton) const {
965 UnicodeString result = skeleton;
966
967 UChar hourMetachar = u'\0';
968 int32_t metacharStart = 0;
969 int32_t metacharCount = 0;
970 for (int32_t i = 0; i < result.length(); i++) {
971 UChar c = result[i];
972 if (c == LOW_J || c == CAP_J || c == CAP_C) {
973 if (hourMetachar == u'\0') {
974 hourMetachar = c;
975 metacharStart = i;
976 }
977 ++metacharCount;
978 } else {
979 if (hourMetachar != u'\0') {
980 break;
981 }
982 }
983 }
984
985 if (hourMetachar != u'\0') {
986 UErrorCode err = U_ZERO_ERROR;
987 UChar hourChar = CAP_H;
988 UChar dayPeriodChar = LOW_A;
989 UnicodeString convertedPattern = DateFormat::getBestPattern(fLocale, UnicodeString(hourMetachar), err);
990
991 if (U_SUCCESS(err)) {
992 // strip literal text from the pattern (so literal characters don't get mistaken for pattern
993 // characters-- such as the 'h' in 'Uhr' in Germam)
994 int32_t firstQuotePos;
995 while ((firstQuotePos = convertedPattern.indexOf(u'\'')) != -1) {
996 int32_t secondQuotePos = convertedPattern.indexOf(u'\'', firstQuotePos + 1);
997 if (secondQuotePos == -1) {
998 secondQuotePos = firstQuotePos;
999 }
1000 convertedPattern.replace(firstQuotePos, (secondQuotePos - firstQuotePos) + 1, UnicodeString());
1001 }
1002
1003 if (convertedPattern.indexOf(LOW_H) != -1) {
1004 hourChar = LOW_H;
1005 } else if (convertedPattern.indexOf(CAP_K) != -1) {
1006 hourChar = CAP_K;
1007 } else if (convertedPattern.indexOf(LOW_K) != -1) {
1008 hourChar = LOW_K;
1009 }
1010
1011 if (convertedPattern.indexOf(LOW_B) != -1) {
1012 dayPeriodChar = LOW_B;
1013 } else if (convertedPattern.indexOf(CAP_B) != -1) {
1014 dayPeriodChar = CAP_B;
1015 }
1016 }
1017
1018 if (hourChar == CAP_H || hourChar == LOW_K) {
1019 result.replace(metacharStart, metacharCount, hourChar);
1020 } else {
1021 UnicodeString hourAndDayPeriod(hourChar);
1022 switch (metacharCount) {
1023 case 1:
1024 case 2:
1025 default:
1026 hourAndDayPeriod.append(UnicodeString(dayPeriodChar));
1027 break;
1028 case 3:
1029 case 4:
1030 for (int32_t i = 0; i < 4; i++) {
1031 hourAndDayPeriod.append(dayPeriodChar);
1032 }
1033 break;
1034 case 5:
1035 case 6:
1036 for (int32_t i = 0; i < 5; i++) {
1037 hourAndDayPeriod.append(dayPeriodChar);
1038 }
1039 break;
1040 }
1041 result.replace(metacharStart, metacharCount, hourAndDayPeriod);
1042 }
1043 }
1044 return result;
1045 }
1046
1047
1048 void U_EXPORT2
getDateTimeSkeleton(const UnicodeString & skeleton,UnicodeString & dateSkeleton,UnicodeString & normalizedDateSkeleton,UnicodeString & timeSkeleton,UnicodeString & normalizedTimeSkeleton)1049 DateIntervalFormat::getDateTimeSkeleton(const UnicodeString& skeleton,
1050 UnicodeString& dateSkeleton,
1051 UnicodeString& normalizedDateSkeleton,
1052 UnicodeString& timeSkeleton,
1053 UnicodeString& normalizedTimeSkeleton) {
1054 // dateSkeleton follows the sequence of y*M*E*d*
1055 // timeSkeleton follows the sequence of hm*[v|z]?
1056 int32_t ECount = 0;
1057 int32_t dCount = 0;
1058 int32_t MCount = 0;
1059 int32_t yCount = 0;
1060 int32_t mCount = 0;
1061 int32_t vCount = 0;
1062 int32_t zCount = 0;
1063 UChar hourChar = u'\0';
1064 int32_t i;
1065
1066 for (i = 0; i < skeleton.length(); ++i) {
1067 UChar ch = skeleton[i];
1068 switch ( ch ) {
1069 case CAP_E:
1070 dateSkeleton.append(ch);
1071 ++ECount;
1072 break;
1073 case LOW_D:
1074 dateSkeleton.append(ch);
1075 ++dCount;
1076 break;
1077 case CAP_M:
1078 dateSkeleton.append(ch);
1079 ++MCount;
1080 break;
1081 case LOW_Y:
1082 dateSkeleton.append(ch);
1083 ++yCount;
1084 break;
1085 case CAP_G:
1086 case CAP_Y:
1087 case LOW_U:
1088 case CAP_Q:
1089 case LOW_Q:
1090 case CAP_L:
1091 case LOW_L:
1092 case CAP_W:
1093 case LOW_W:
1094 case CAP_D:
1095 case CAP_F:
1096 case LOW_G:
1097 case LOW_E:
1098 case LOW_C:
1099 case CAP_U:
1100 case LOW_R:
1101 normalizedDateSkeleton.append(ch);
1102 dateSkeleton.append(ch);
1103 break;
1104 case LOW_H:
1105 case CAP_H:
1106 case LOW_K:
1107 case CAP_K:
1108 timeSkeleton.append(ch);
1109 if (hourChar == u'\0') {
1110 hourChar = ch;
1111 }
1112 break;
1113 case LOW_M:
1114 timeSkeleton.append(ch);
1115 ++mCount;
1116 break;
1117 case LOW_Z:
1118 ++zCount;
1119 timeSkeleton.append(ch);
1120 break;
1121 case LOW_V:
1122 ++vCount;
1123 timeSkeleton.append(ch);
1124 break;
1125 case LOW_A:
1126 case CAP_V:
1127 case CAP_Z:
1128 case LOW_J:
1129 case LOW_S:
1130 case CAP_S:
1131 case CAP_A:
1132 case LOW_B:
1133 case CAP_B:
1134 timeSkeleton.append(ch);
1135 normalizedTimeSkeleton.append(ch);
1136 break;
1137 }
1138 }
1139
1140 /* generate normalized form for date*/
1141 if ( yCount != 0 ) {
1142 for (i = 0; i < yCount; ++i) {
1143 normalizedDateSkeleton.append(LOW_Y);
1144 }
1145 }
1146 if ( MCount != 0 ) {
1147 if ( MCount < 3 ) {
1148 normalizedDateSkeleton.append(CAP_M);
1149 } else {
1150 for ( int32_t j = 0; j < MCount && j < MAX_M_COUNT; ++j) {
1151 normalizedDateSkeleton.append(CAP_M);
1152 }
1153 }
1154 }
1155 if ( ECount != 0 ) {
1156 if ( ECount <= 3 ) {
1157 normalizedDateSkeleton.append(CAP_E);
1158 } else {
1159 for ( int32_t j = 0; j < ECount && j < MAX_E_COUNT; ++j ) {
1160 normalizedDateSkeleton.append(CAP_E);
1161 }
1162 }
1163 }
1164 if ( dCount != 0 ) {
1165 normalizedDateSkeleton.append(LOW_D);
1166 }
1167
1168 /* generate normalized form for time */
1169 if ( hourChar != u'\0' ) {
1170 normalizedTimeSkeleton.append(hourChar);
1171 }
1172 if ( mCount != 0 ) {
1173 normalizedTimeSkeleton.append(LOW_M);
1174 }
1175 if ( zCount != 0 ) {
1176 normalizedTimeSkeleton.append(LOW_Z);
1177 }
1178 if ( vCount != 0 ) {
1179 normalizedTimeSkeleton.append(LOW_V);
1180 }
1181 }
1182
1183
1184 /**
1185 * Generate date or time interval pattern from resource,
1186 * and set them into the interval pattern locale to this formatter.
1187 *
1188 * It needs to handle the following:
1189 * 1. need to adjust field width.
1190 * For example, the interval patterns saved in DateIntervalInfo
1191 * includes "dMMMy", but not "dMMMMy".
1192 * Need to get interval patterns for dMMMMy from dMMMy.
1193 * Another example, the interval patterns saved in DateIntervalInfo
1194 * includes "hmv", but not "hmz".
1195 * Need to get interval patterns for "hmz' from 'hmv'
1196 *
1197 * 2. there might be no pattern for 'y' differ for skeleton "Md",
1198 * in order to get interval patterns for 'y' differ,
1199 * need to look for it from skeleton 'yMd'
1200 *
1201 * @param dateSkeleton normalized date skeleton
1202 * @param timeSkeleton normalized time skeleton
1203 * @return whether the resource is found for the skeleton.
1204 * TRUE if interval pattern found for the skeleton,
1205 * FALSE otherwise.
1206 * @stable ICU 4.0
1207 */
1208 UBool
setSeparateDateTimePtn(const UnicodeString & dateSkeleton,const UnicodeString & timeSkeleton)1209 DateIntervalFormat::setSeparateDateTimePtn(
1210 const UnicodeString& dateSkeleton,
1211 const UnicodeString& timeSkeleton) {
1212 const UnicodeString* skeleton;
1213 // if both date and time skeleton present,
1214 // the final interval pattern might include time interval patterns
1215 // ( when, am_pm, hour, minute differ ),
1216 // but not date interval patterns ( when year, month, day differ ).
1217 // For year/month/day differ, it falls back to fall-back pattern.
1218 if ( timeSkeleton.length() != 0 ) {
1219 skeleton = &timeSkeleton;
1220 } else {
1221 skeleton = &dateSkeleton;
1222 }
1223
1224 /* interval patterns for skeleton "dMMMy" (but not "dMMMMy")
1225 * are defined in resource,
1226 * interval patterns for skeleton "dMMMMy" are calculated by
1227 * 1. get the best match skeleton for "dMMMMy", which is "dMMMy"
1228 * 2. get the interval patterns for "dMMMy",
1229 * 3. extend "MMM" to "MMMM" in above interval patterns for "dMMMMy"
1230 * getBestSkeleton() is step 1.
1231 */
1232 // best skeleton, and the difference information
1233 int8_t differenceInfo = 0;
1234 const UnicodeString* bestSkeleton = fInfo->getBestSkeleton(*skeleton,
1235 differenceInfo);
1236 /* best skeleton could be nullptr.
1237 For example: in "ca" resource file,
1238 interval format is defined as following
1239 intervalFormats{
1240 fallback{"{0} - {1}"}
1241 }
1242 there is no skeletons/interval patterns defined,
1243 and the best skeleton match could be nullptr
1244 */
1245 if ( bestSkeleton == nullptr ) {
1246 return false;
1247 }
1248
1249 // Set patterns for fallback use, need to do this
1250 // before returning if differenceInfo == -1
1251 UErrorCode status;
1252 if ( dateSkeleton.length() != 0) {
1253 status = U_ZERO_ERROR;
1254 fDatePattern = new UnicodeString(DateFormat::getBestPattern(
1255 fLocale, dateSkeleton, status));
1256 // no way to report OOM. :(
1257 }
1258 if ( timeSkeleton.length() != 0) {
1259 status = U_ZERO_ERROR;
1260 fTimePattern = new UnicodeString(DateFormat::getBestPattern(
1261 fLocale, timeSkeleton, status));
1262 // no way to report OOM. :(
1263 }
1264
1265 // difference:
1266 // 0 means the best matched skeleton is the same as input skeleton
1267 // 1 means the fields are the same, but field width are different
1268 // 2 means the only difference between fields are v/z,
1269 // -1 means there are other fields difference
1270 // (this will happen, for instance, if the supplied skeleton has seconds,
1271 // but no skeletons in the intervalFormats data do)
1272 if ( differenceInfo == -1 ) {
1273 // skeleton has different fields, not only v/z difference
1274 return false;
1275 }
1276
1277 if ( timeSkeleton.length() == 0 ) {
1278 UnicodeString extendedSkeleton;
1279 UnicodeString extendedBestSkeleton;
1280 // only has date skeleton
1281 setIntervalPattern(UCAL_DATE, skeleton, bestSkeleton, differenceInfo,
1282 &extendedSkeleton, &extendedBestSkeleton);
1283
1284 UBool extended = setIntervalPattern(UCAL_MONTH, skeleton, bestSkeleton,
1285 differenceInfo,
1286 &extendedSkeleton, &extendedBestSkeleton);
1287
1288 if ( extended ) {
1289 bestSkeleton = &extendedBestSkeleton;
1290 skeleton = &extendedSkeleton;
1291 }
1292 setIntervalPattern(UCAL_YEAR, skeleton, bestSkeleton, differenceInfo,
1293 &extendedSkeleton, &extendedBestSkeleton);
1294 setIntervalPattern(UCAL_ERA, skeleton, bestSkeleton, differenceInfo,
1295 &extendedSkeleton, &extendedBestSkeleton);
1296 } else {
1297 setIntervalPattern(UCAL_MINUTE, skeleton, bestSkeleton, differenceInfo);
1298 setIntervalPattern(UCAL_HOUR, skeleton, bestSkeleton, differenceInfo);
1299 setIntervalPattern(UCAL_AM_PM, skeleton, bestSkeleton, differenceInfo);
1300 }
1301 return true;
1302 }
1303
1304
1305
1306 void
setFallbackPattern(UCalendarDateFields field,const UnicodeString & skeleton,UErrorCode & status)1307 DateIntervalFormat::setFallbackPattern(UCalendarDateFields field,
1308 const UnicodeString& skeleton,
1309 UErrorCode& status) {
1310 if ( U_FAILURE(status) ) {
1311 return;
1312 }
1313 UnicodeString pattern = DateFormat::getBestPattern(
1314 fLocale, skeleton, status);
1315 if ( U_FAILURE(status) ) {
1316 return;
1317 }
1318 setPatternInfo(field, nullptr, &pattern, fInfo->getDefaultOrder());
1319 }
1320
1321
1322
1323
1324 void
setPatternInfo(UCalendarDateFields field,const UnicodeString * firstPart,const UnicodeString * secondPart,UBool laterDateFirst)1325 DateIntervalFormat::setPatternInfo(UCalendarDateFields field,
1326 const UnicodeString* firstPart,
1327 const UnicodeString* secondPart,
1328 UBool laterDateFirst) {
1329 // for fall back interval patterns,
1330 // the first part of the pattern is empty,
1331 // the second part of the pattern is the full-pattern
1332 // should be used in fall-back.
1333 UErrorCode status = U_ZERO_ERROR;
1334 // following should not set any wrong status.
1335 int32_t itvPtnIndex = DateIntervalInfo::calendarFieldToIntervalIndex(field,
1336 status);
1337 if ( U_FAILURE(status) ) {
1338 return;
1339 }
1340 PatternInfo& ptn = fIntervalPatterns[itvPtnIndex];
1341 if ( firstPart ) {
1342 ptn.firstPart = *firstPart;
1343 }
1344 if ( secondPart ) {
1345 ptn.secondPart = *secondPart;
1346 }
1347 ptn.laterDateFirst = laterDateFirst;
1348 }
1349
1350 void
setIntervalPattern(UCalendarDateFields field,const UnicodeString & intervalPattern)1351 DateIntervalFormat::setIntervalPattern(UCalendarDateFields field,
1352 const UnicodeString& intervalPattern) {
1353 UBool order = fInfo->getDefaultOrder();
1354 setIntervalPattern(field, intervalPattern, order);
1355 }
1356
1357
1358 void
setIntervalPattern(UCalendarDateFields field,const UnicodeString & intervalPattern,UBool laterDateFirst)1359 DateIntervalFormat::setIntervalPattern(UCalendarDateFields field,
1360 const UnicodeString& intervalPattern,
1361 UBool laterDateFirst) {
1362 const UnicodeString* pattern = &intervalPattern;
1363 UBool order = laterDateFirst;
1364 // check for "latestFirst:" or "earliestFirst:" prefix
1365 int8_t prefixLength = UPRV_LENGTHOF(gLaterFirstPrefix);
1366 int8_t earliestFirstLength = UPRV_LENGTHOF(gEarlierFirstPrefix);
1367 UnicodeString realPattern;
1368 if ( intervalPattern.startsWith(gLaterFirstPrefix, prefixLength) ) {
1369 order = true;
1370 intervalPattern.extract(prefixLength,
1371 intervalPattern.length() - prefixLength,
1372 realPattern);
1373 pattern = &realPattern;
1374 } else if ( intervalPattern.startsWith(gEarlierFirstPrefix,
1375 earliestFirstLength) ) {
1376 order = false;
1377 intervalPattern.extract(earliestFirstLength,
1378 intervalPattern.length() - earliestFirstLength,
1379 realPattern);
1380 pattern = &realPattern;
1381 }
1382
1383 int32_t splitPoint = splitPatternInto2Part(*pattern);
1384
1385 UnicodeString firstPart;
1386 UnicodeString secondPart;
1387 pattern->extract(0, splitPoint, firstPart);
1388 if ( splitPoint < pattern->length() ) {
1389 pattern->extract(splitPoint, pattern->length()-splitPoint, secondPart);
1390 }
1391 setPatternInfo(field, &firstPart, &secondPart, order);
1392 }
1393
1394
1395
1396
1397 /**
1398 * Generate interval pattern from existing resource
1399 *
1400 * It not only save the interval patterns,
1401 * but also return the extended skeleton and its best match skeleton.
1402 *
1403 * @param field largest different calendar field
1404 * @param skeleton skeleton
1405 * @param bestSkeleton the best match skeleton which has interval pattern
1406 * defined in resource
1407 * @param differenceInfo the difference between skeleton and best skeleton
1408 * 0 means the best matched skeleton is the same as input skeleton
1409 * 1 means the fields are the same, but field width are different
1410 * 2 means the only difference between fields are v/z,
1411 * -1 means there are other fields difference
1412 *
1413 * @param extendedSkeleton extended skeleton
1414 * @param extendedBestSkeleton extended best match skeleton
1415 * @return whether the interval pattern is found
1416 * through extending skeleton or not.
1417 * TRUE if interval pattern is found by
1418 * extending skeleton, FALSE otherwise.
1419 * @stable ICU 4.0
1420 */
1421 UBool
setIntervalPattern(UCalendarDateFields field,const UnicodeString * skeleton,const UnicodeString * bestSkeleton,int8_t differenceInfo,UnicodeString * extendedSkeleton,UnicodeString * extendedBestSkeleton)1422 DateIntervalFormat::setIntervalPattern(UCalendarDateFields field,
1423 const UnicodeString* skeleton,
1424 const UnicodeString* bestSkeleton,
1425 int8_t differenceInfo,
1426 UnicodeString* extendedSkeleton,
1427 UnicodeString* extendedBestSkeleton) {
1428 UErrorCode status = U_ZERO_ERROR;
1429 // following getIntervalPattern() should not generate error status
1430 UnicodeString pattern;
1431 fInfo->getIntervalPattern(*bestSkeleton, field, pattern, status);
1432 if ( pattern.isEmpty() ) {
1433 // single date
1434 if ( SimpleDateFormat::isFieldUnitIgnored(*bestSkeleton, field) ) {
1435 // do nothing, format will handle it
1436 return false;
1437 }
1438
1439 // for 24 hour system, interval patterns in resource file
1440 // might not include pattern when am_pm differ,
1441 // which should be the same as hour differ.
1442 // add it here for simplicity
1443 if ( field == UCAL_AM_PM ) {
1444 fInfo->getIntervalPattern(*bestSkeleton, UCAL_HOUR, pattern,status);
1445 if ( !pattern.isEmpty() ) {
1446 UBool suppressDayPeriodField = fSkeleton.indexOf(CAP_J) != -1;
1447 UnicodeString adjustIntervalPattern;
1448 adjustFieldWidth(*skeleton, *bestSkeleton, pattern, differenceInfo,
1449 suppressDayPeriodField, adjustIntervalPattern);
1450 setIntervalPattern(field, adjustIntervalPattern);
1451 }
1452 return false;
1453 }
1454 // else, looking for pattern when 'y' differ for 'dMMMM' skeleton,
1455 // first, get best match pattern "MMMd",
1456 // since there is no pattern for 'y' differs for skeleton 'MMMd',
1457 // need to look for it from skeleton 'yMMMd',
1458 // if found, adjust field width in interval pattern from
1459 // "MMM" to "MMMM".
1460 UChar fieldLetter = fgCalendarFieldToPatternLetter[field];
1461 if ( extendedSkeleton ) {
1462 *extendedSkeleton = *skeleton;
1463 *extendedBestSkeleton = *bestSkeleton;
1464 extendedSkeleton->insert(0, fieldLetter);
1465 extendedBestSkeleton->insert(0, fieldLetter);
1466 // for example, looking for patterns when 'y' differ for
1467 // skeleton "MMMM".
1468 fInfo->getIntervalPattern(*extendedBestSkeleton,field,pattern,status);
1469 if ( pattern.isEmpty() && differenceInfo == 0 ) {
1470 // if there is no skeleton "yMMMM" defined,
1471 // look for the best match skeleton, for example: "yMMM"
1472 const UnicodeString* tmpBest = fInfo->getBestSkeleton(
1473 *extendedBestSkeleton, differenceInfo);
1474 if ( tmpBest != 0 && differenceInfo != -1 ) {
1475 fInfo->getIntervalPattern(*tmpBest, field, pattern, status);
1476 bestSkeleton = tmpBest;
1477 }
1478 }
1479 }
1480 }
1481 if ( !pattern.isEmpty() ) {
1482 UBool suppressDayPeriodField = fSkeleton.indexOf(CAP_J) != -1;
1483 if ( differenceInfo != 0 || suppressDayPeriodField) {
1484 UnicodeString adjustIntervalPattern;
1485 adjustFieldWidth(*skeleton, *bestSkeleton, pattern, differenceInfo,
1486 suppressDayPeriodField, adjustIntervalPattern);
1487 setIntervalPattern(field, adjustIntervalPattern);
1488 } else {
1489 setIntervalPattern(field, pattern);
1490 }
1491 if ( extendedSkeleton && !extendedSkeleton->isEmpty() ) {
1492 return TRUE;
1493 }
1494 }
1495 return FALSE;
1496 }
1497
1498
1499
1500 int32_t U_EXPORT2
splitPatternInto2Part(const UnicodeString & intervalPattern)1501 DateIntervalFormat::splitPatternInto2Part(const UnicodeString& intervalPattern) {
1502 UBool inQuote = false;
1503 UChar prevCh = 0;
1504 int32_t count = 0;
1505
1506 /* repeatedPattern used to record whether a pattern has already seen.
1507 It is a pattern applies to first calendar if it is first time seen,
1508 otherwise, it is a pattern applies to the second calendar
1509 */
1510 UBool patternRepeated[] =
1511 {
1512 // A B C D E F G H I J K L M N O
1513 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1514 // P Q R S T U V W X Y Z
1515 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1516 // a b c d e f g h i j k l m n o
1517 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1518 // p q r s t u v w x y z
1519 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
1520 };
1521
1522 int8_t PATTERN_CHAR_BASE = 0x41;
1523
1524 /* loop through the pattern string character by character looking for
1525 * the first repeated pattern letter, which breaks the interval pattern
1526 * into 2 parts.
1527 */
1528 int32_t i;
1529 UBool foundRepetition = false;
1530 for (i = 0; i < intervalPattern.length(); ++i) {
1531 UChar ch = intervalPattern.charAt(i);
1532
1533 if (ch != prevCh && count > 0) {
1534 // check the repeativeness of pattern letter
1535 UBool repeated = patternRepeated[(int)(prevCh - PATTERN_CHAR_BASE)];
1536 if ( repeated == FALSE ) {
1537 patternRepeated[prevCh - PATTERN_CHAR_BASE] = TRUE;
1538 } else {
1539 foundRepetition = true;
1540 break;
1541 }
1542 count = 0;
1543 }
1544 if (ch == 0x0027 /*'*/) {
1545 // Consecutive single quotes are a single quote literal,
1546 // either outside of quotes or between quotes
1547 if ((i+1) < intervalPattern.length() &&
1548 intervalPattern.charAt(i+1) == 0x0027 /*'*/) {
1549 ++i;
1550 } else {
1551 inQuote = ! inQuote;
1552 }
1553 }
1554 else if (!inQuote && ((ch >= 0x0061 /*'a'*/ && ch <= 0x007A /*'z'*/)
1555 || (ch >= 0x0041 /*'A'*/ && ch <= 0x005A /*'Z'*/))) {
1556 // ch is a date-time pattern character
1557 prevCh = ch;
1558 ++count;
1559 }
1560 }
1561 // check last pattern char, distinguish
1562 // "dd MM" ( no repetition ),
1563 // "d-d"(last char repeated ), and
1564 // "d-d MM" ( repetition found )
1565 if ( count > 0 && foundRepetition == FALSE ) {
1566 if ( patternRepeated[(int)(prevCh - PATTERN_CHAR_BASE)] == FALSE ) {
1567 count = 0;
1568 }
1569 }
1570 return (i - count);
1571 }
1572
1573 // The following is only called from fallbackFormat, i.e. within the gFormatterMutex lock
fallbackFormatRange(Calendar & fromCalendar,Calendar & toCalendar,UnicodeString & appendTo,int8_t & firstIndex,FieldPositionHandler & fphandler,UErrorCode & status) const1574 void DateIntervalFormat::fallbackFormatRange(
1575 Calendar& fromCalendar,
1576 Calendar& toCalendar,
1577 UnicodeString& appendTo,
1578 int8_t& firstIndex,
1579 FieldPositionHandler& fphandler,
1580 UErrorCode& status) const {
1581 UnicodeString fallbackPattern;
1582 fInfo->getFallbackIntervalPattern(fallbackPattern);
1583 SimpleFormatter sf(fallbackPattern, 2, 2, status);
1584 if (U_FAILURE(status)) {
1585 return;
1586 }
1587 int32_t offsets[2];
1588 UnicodeString patternBody = sf.getTextWithNoArguments(offsets, 2);
1589
1590 UErrorCode tempStatus = U_ZERO_ERROR; // for setContext, ignored
1591 // TODO(ICU-20406): Use SimpleFormatter Iterator interface when available.
1592 if (offsets[0] < offsets[1]) {
1593 firstIndex = 0;
1594 appendTo.append(patternBody.tempSubStringBetween(0, offsets[0]));
1595 fDateFormat->_format(fromCalendar, appendTo, fphandler, status);
1596 appendTo.append(patternBody.tempSubStringBetween(offsets[0], offsets[1]));
1597 // No capitalization for second part of interval
1598 fDateFormat->setContext(UDISPCTX_CAPITALIZATION_NONE, tempStatus);
1599 fDateFormat->_format(toCalendar, appendTo, fphandler, status);
1600 appendTo.append(patternBody.tempSubStringBetween(offsets[1]));
1601 } else {
1602 firstIndex = 1;
1603 appendTo.append(patternBody.tempSubStringBetween(0, offsets[1]));
1604 fDateFormat->_format(toCalendar, appendTo, fphandler, status);
1605 appendTo.append(patternBody.tempSubStringBetween(offsets[1], offsets[0]));
1606 // No capitalization for second part of interval
1607 fDateFormat->setContext(UDISPCTX_CAPITALIZATION_NONE, tempStatus);
1608 fDateFormat->_format(fromCalendar, appendTo, fphandler, status);
1609 appendTo.append(patternBody.tempSubStringBetween(offsets[0]));
1610 }
1611 }
1612
1613 // The following is only called from formatImpl, i.e. within the gFormatterMutex lock
1614 UnicodeString&
fallbackFormat(Calendar & fromCalendar,Calendar & toCalendar,UBool fromToOnSameDay,UnicodeString & appendTo,int8_t & firstIndex,FieldPositionHandler & fphandler,UErrorCode & status) const1615 DateIntervalFormat::fallbackFormat(Calendar& fromCalendar,
1616 Calendar& toCalendar,
1617 UBool fromToOnSameDay, // new
1618 UnicodeString& appendTo,
1619 int8_t& firstIndex,
1620 FieldPositionHandler& fphandler,
1621 UErrorCode& status) const {
1622 if ( U_FAILURE(status) ) {
1623 return appendTo;
1624 }
1625
1626 UBool formatDatePlusTimeRange = (fromToOnSameDay && fDatePattern && fTimePattern);
1627 if (formatDatePlusTimeRange) {
1628 SimpleFormatter sf(*fDateTimeFormat, 2, 2, status);
1629 if (U_FAILURE(status)) {
1630 return appendTo;
1631 }
1632 int32_t offsets[2];
1633 UnicodeString patternBody = sf.getTextWithNoArguments(offsets, 2);
1634
1635 UnicodeString fullPattern; // for saving the pattern in fDateFormat
1636 fDateFormat->toPattern(fullPattern); // save current pattern, restore later
1637
1638 UErrorCode tempStatus = U_ZERO_ERROR; // for setContext, ignored
1639 // {0} is time range
1640 // {1} is single date portion
1641 // TODO(ICU-20406): Use SimpleFormatter Iterator interface when available.
1642 if (offsets[0] < offsets[1]) {
1643 appendTo.append(patternBody.tempSubStringBetween(0, offsets[0]));
1644 fDateFormat->applyPattern(*fTimePattern);
1645 fallbackFormatRange(fromCalendar, toCalendar, appendTo, firstIndex, fphandler, status);
1646 appendTo.append(patternBody.tempSubStringBetween(offsets[0], offsets[1]));
1647 fDateFormat->applyPattern(*fDatePattern);
1648 // No capitalization for second portion
1649 fDateFormat->setContext(UDISPCTX_CAPITALIZATION_NONE, tempStatus);
1650 fDateFormat->_format(fromCalendar, appendTo, fphandler, status);
1651 appendTo.append(patternBody.tempSubStringBetween(offsets[1]));
1652 } else {
1653 appendTo.append(patternBody.tempSubStringBetween(0, offsets[1]));
1654 fDateFormat->applyPattern(*fDatePattern);
1655 fDateFormat->_format(fromCalendar, appendTo, fphandler, status);
1656 appendTo.append(patternBody.tempSubStringBetween(offsets[1], offsets[0]));
1657 fDateFormat->applyPattern(*fTimePattern);
1658 // No capitalization for second portion
1659 fDateFormat->setContext(UDISPCTX_CAPITALIZATION_NONE, tempStatus);
1660 fallbackFormatRange(fromCalendar, toCalendar, appendTo, firstIndex, fphandler, status);
1661 appendTo.append(patternBody.tempSubStringBetween(offsets[0]));
1662 }
1663
1664 // restore full pattern
1665 fDateFormat->applyPattern(fullPattern);
1666 } else {
1667 fallbackFormatRange(fromCalendar, toCalendar, appendTo, firstIndex, fphandler, status);
1668 }
1669 return appendTo;
1670 }
1671
1672
1673
1674
1675 UBool U_EXPORT2
fieldExistsInSkeleton(UCalendarDateFields field,const UnicodeString & skeleton)1676 DateIntervalFormat::fieldExistsInSkeleton(UCalendarDateFields field,
1677 const UnicodeString& skeleton)
1678 {
1679 const UChar fieldChar = fgCalendarFieldToPatternLetter[field];
1680 return ( (skeleton.indexOf(fieldChar) == -1)?FALSE:TRUE ) ;
1681 }
1682
1683
1684
1685 void U_EXPORT2
adjustFieldWidth(const UnicodeString & inputSkeleton,const UnicodeString & bestMatchSkeleton,const UnicodeString & bestIntervalPattern,int8_t differenceInfo,UBool suppressDayPeriodField,UnicodeString & adjustedPtn)1686 DateIntervalFormat::adjustFieldWidth(const UnicodeString& inputSkeleton,
1687 const UnicodeString& bestMatchSkeleton,
1688 const UnicodeString& bestIntervalPattern,
1689 int8_t differenceInfo,
1690 UBool suppressDayPeriodField,
1691 UnicodeString& adjustedPtn) {
1692 adjustedPtn = bestIntervalPattern;
1693 int32_t inputSkeletonFieldWidth[] =
1694 {
1695 // A B C D E F G H I J K L M N O
1696 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1697 // P Q R S T U V W X Y Z
1698 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1699 // a b c d e f g h i j k l m n o
1700 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1701 // p q r s t u v w x y z
1702 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
1703 };
1704
1705 int32_t bestMatchSkeletonFieldWidth[] =
1706 {
1707 // A B C D E F G H I J K L M N O
1708 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1709 // P Q R S T U V W X Y Z
1710 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1711 // a b c d e f g h i j k l m n o
1712 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1713 // p q r s t u v w x y z
1714 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
1715 };
1716
1717 const int8_t PATTERN_CHAR_BASE = 0x41;
1718
1719 DateIntervalInfo::parseSkeleton(inputSkeleton, inputSkeletonFieldWidth);
1720 DateIntervalInfo::parseSkeleton(bestMatchSkeleton, bestMatchSkeletonFieldWidth);
1721 if (suppressDayPeriodField) {
1722 findReplaceInPattern(adjustedPtn, UnicodeString(LOW_A), UnicodeString());
1723 findReplaceInPattern(adjustedPtn, UnicodeString(" "), UnicodeString(" "));
1724 adjustedPtn.trim();
1725 }
1726 if ( differenceInfo == 2 ) {
1727 if (inputSkeleton.indexOf(LOW_Z) != -1) {
1728 findReplaceInPattern(adjustedPtn, UnicodeString(LOW_V), UnicodeString(LOW_Z));
1729 }
1730 if (inputSkeleton.indexOf(CAP_K) != -1) {
1731 findReplaceInPattern(adjustedPtn, UnicodeString(LOW_H), UnicodeString(CAP_K));
1732 }
1733 if (inputSkeleton.indexOf(LOW_K) != -1) {
1734 findReplaceInPattern(adjustedPtn, UnicodeString(CAP_H), UnicodeString(LOW_K));
1735 }
1736 if (inputSkeleton.indexOf(LOW_B) != -1) {
1737 findReplaceInPattern(adjustedPtn, UnicodeString(LOW_A), UnicodeString(LOW_B));
1738 }
1739 }
1740 if (adjustedPtn.indexOf(LOW_A) != -1 && bestMatchSkeletonFieldWidth[LOW_A - PATTERN_CHAR_BASE] == 0) {
1741 bestMatchSkeletonFieldWidth[LOW_A - PATTERN_CHAR_BASE] = 1;
1742 }
1743 if (adjustedPtn.indexOf(LOW_B) != -1 && bestMatchSkeletonFieldWidth[LOW_B - PATTERN_CHAR_BASE] == 0) {
1744 bestMatchSkeletonFieldWidth[LOW_B - PATTERN_CHAR_BASE] = 1;
1745 }
1746
1747 UBool inQuote = false;
1748 UChar prevCh = 0;
1749 int32_t count = 0;
1750
1751 // loop through the pattern string character by character
1752 int32_t adjustedPtnLength = adjustedPtn.length();
1753 int32_t i;
1754 for (i = 0; i < adjustedPtnLength; ++i) {
1755 UChar ch = adjustedPtn.charAt(i);
1756 if (ch != prevCh && count > 0) {
1757 // check the repeativeness of pattern letter
1758 UChar skeletonChar = prevCh;
1759 if ( skeletonChar == CAP_L ) {
1760 // there is no "L" (always be "M") in skeleton,
1761 // but there is "L" in pattern.
1762 // for skeleton "M+", the pattern might be "...L..."
1763 skeletonChar = CAP_M;
1764 }
1765 int32_t fieldCount = bestMatchSkeletonFieldWidth[(int)(skeletonChar - PATTERN_CHAR_BASE)];
1766 int32_t inputFieldCount = inputSkeletonFieldWidth[(int)(skeletonChar - PATTERN_CHAR_BASE)];
1767 if ( fieldCount == count && inputFieldCount > fieldCount ) {
1768 count = inputFieldCount - fieldCount;
1769 int32_t j;
1770 for ( j = 0; j < count; ++j ) {
1771 adjustedPtn.insert(i, prevCh);
1772 }
1773 i += count;
1774 adjustedPtnLength += count;
1775 }
1776 count = 0;
1777 }
1778 if (ch == 0x0027 /*'*/) {
1779 // Consecutive single quotes are a single quote literal,
1780 // either outside of quotes or between quotes
1781 if ((i+1) < adjustedPtn.length() && adjustedPtn.charAt(i+1) == 0x0027 /* ' */) {
1782 ++i;
1783 } else {
1784 inQuote = ! inQuote;
1785 }
1786 }
1787 else if ( ! inQuote && ((ch >= 0x0061 /*'a'*/ && ch <= 0x007A /*'z'*/)
1788 || (ch >= 0x0041 /*'A'*/ && ch <= 0x005A /*'Z'*/))) {
1789 // ch is a date-time pattern character
1790 prevCh = ch;
1791 ++count;
1792 }
1793 }
1794 if ( count > 0 ) {
1795 // last item
1796 // check the repeativeness of pattern letter
1797 UChar skeletonChar = prevCh;
1798 if ( skeletonChar == CAP_L ) {
1799 // there is no "L" (always be "M") in skeleton,
1800 // but there is "L" in pattern.
1801 // for skeleton "M+", the pattern might be "...L..."
1802 skeletonChar = CAP_M;
1803 }
1804 int32_t fieldCount = bestMatchSkeletonFieldWidth[(int)(skeletonChar - PATTERN_CHAR_BASE)];
1805 int32_t inputFieldCount = inputSkeletonFieldWidth[(int)(skeletonChar - PATTERN_CHAR_BASE)];
1806 if ( fieldCount == count && inputFieldCount > fieldCount ) {
1807 count = inputFieldCount - fieldCount;
1808 int32_t j;
1809 for ( j = 0; j < count; ++j ) {
1810 adjustedPtn.append(prevCh);
1811 }
1812 }
1813 }
1814 }
1815
1816 void
findReplaceInPattern(UnicodeString & targetString,const UnicodeString & strToReplace,const UnicodeString & strToReplaceWith)1817 DateIntervalFormat::findReplaceInPattern(UnicodeString& targetString,
1818 const UnicodeString& strToReplace,
1819 const UnicodeString& strToReplaceWith) {
1820 int32_t firstQuoteIndex = targetString.indexOf(u'\'');
1821 if (firstQuoteIndex == -1) {
1822 targetString.findAndReplace(strToReplace, strToReplaceWith);
1823 } else {
1824 UnicodeString result;
1825 UnicodeString source = targetString;
1826
1827 while (firstQuoteIndex >= 0) {
1828 int32_t secondQuoteIndex = source.indexOf(u'\'', firstQuoteIndex + 1);
1829 if (secondQuoteIndex == -1) {
1830 secondQuoteIndex = source.length() - 1;
1831 }
1832
1833 UnicodeString unquotedText(source, 0, firstQuoteIndex);
1834 UnicodeString quotedText(source, firstQuoteIndex, secondQuoteIndex - firstQuoteIndex + 1);
1835
1836 unquotedText.findAndReplace(strToReplace, strToReplaceWith);
1837 result += unquotedText;
1838 result += quotedText;
1839
1840 source.remove(0, secondQuoteIndex + 1);
1841 firstQuoteIndex = source.indexOf(u'\'');
1842 }
1843 source.findAndReplace(strToReplace, strToReplaceWith);
1844 result += source;
1845 targetString = result;
1846 }
1847 }
1848
1849
1850
1851 void
concatSingleDate2TimeInterval(UnicodeString & format,const UnicodeString & datePattern,UCalendarDateFields field,UErrorCode & status)1852 DateIntervalFormat::concatSingleDate2TimeInterval(UnicodeString& format,
1853 const UnicodeString& datePattern,
1854 UCalendarDateFields field,
1855 UErrorCode& status) {
1856 // following should not set wrong status
1857 int32_t itvPtnIndex = DateIntervalInfo::calendarFieldToIntervalIndex(field,
1858 status);
1859 if ( U_FAILURE(status) ) {
1860 return;
1861 }
1862 PatternInfo& timeItvPtnInfo = fIntervalPatterns[itvPtnIndex];
1863 if ( !timeItvPtnInfo.firstPart.isEmpty() ) {
1864 UnicodeString timeIntervalPattern(timeItvPtnInfo.firstPart);
1865 timeIntervalPattern.append(timeItvPtnInfo.secondPart);
1866 UnicodeString combinedPattern;
1867 SimpleFormatter(format, 2, 2, status).
1868 format(timeIntervalPattern, datePattern, combinedPattern, status);
1869 if ( U_FAILURE(status) ) {
1870 return;
1871 }
1872 setIntervalPattern(field, combinedPattern, timeItvPtnInfo.laterDateFirst);
1873 }
1874 // else: fall back
1875 // it should not happen if the interval format defined is valid
1876 }
1877
1878
1879
1880 const UChar
1881 DateIntervalFormat::fgCalendarFieldToPatternLetter[] =
1882 {
1883 /*GyM*/ CAP_G, LOW_Y, CAP_M,
1884 /*wWd*/ LOW_W, CAP_W, LOW_D,
1885 /*DEF*/ CAP_D, CAP_E, CAP_F,
1886 /*ahH*/ LOW_A, LOW_H, CAP_H,
1887 /*msS*/ LOW_M, LOW_S, CAP_S, // MINUTE, SECOND, MILLISECOND
1888 /*z.Y*/ LOW_Z, SPACE, CAP_Y, // ZONE_OFFSET, DST_OFFSET, YEAR_WOY,
1889 /*eug*/ LOW_E, LOW_U, LOW_G, // DOW_LOCAL, EXTENDED_YEAR, JULIAN_DAY,
1890 /*A..*/ CAP_A, SPACE, SPACE, // MILLISECONDS_IN_DAY, IS_LEAP_MONTH, FIELD_COUNT
1891 };
1892
1893
1894
1895 U_NAMESPACE_END
1896
1897 #endif
1898