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 char16_t 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 char16_t 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 char16_t 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 snprintf(mesg, sizeof(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 bool
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 snprintf(mesg, sizeof(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 snprintf(mesg, sizeof(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 char16_t* 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 char16_t hourMetachar = u'\0';
968 char16_t dayPeriodChar = u'\0';
969 int32_t hourFieldStart = 0;
970 int32_t hourFieldLength = 0;
971 int32_t dayPeriodStart = 0;
972 int32_t dayPeriodLength = 0;
973 for (int32_t i = 0; i < result.length(); i++) {
974 char16_t c = result[i];
975 if (c == LOW_J || c == CAP_J || c == CAP_C || c == LOW_H || c == CAP_H || c == LOW_K || c == CAP_K) {
976 if (hourMetachar == u'\0') {
977 hourMetachar = c;
978 hourFieldStart = i;
979 }
980 ++hourFieldLength;
981 } else if (c == LOW_A || c == LOW_B || c == CAP_B) {
982 if (dayPeriodChar == u'\0') {
983 dayPeriodChar = c;
984 dayPeriodStart = i;
985 }
986 ++dayPeriodLength;
987 } else {
988 if (hourMetachar != u'\0' && dayPeriodChar != u'\0') {
989 break;
990 }
991 }
992 }
993
994 if (hourMetachar != u'\0') {
995 UErrorCode err = U_ZERO_ERROR;
996 char16_t hourChar = CAP_H;
997 UnicodeString convertedPattern = DateFormat::getBestPattern(fLocale, UnicodeString(hourMetachar), err);
998
999 if (U_SUCCESS(err)) {
1000 // strip literal text from the pattern (so literal characters don't get mistaken for pattern
1001 // characters-- such as the 'h' in 'Uhr' in Germam)
1002 int32_t firstQuotePos;
1003 while ((firstQuotePos = convertedPattern.indexOf(u'\'')) != -1) {
1004 int32_t secondQuotePos = convertedPattern.indexOf(u'\'', firstQuotePos + 1);
1005 if (secondQuotePos == -1) {
1006 secondQuotePos = firstQuotePos;
1007 }
1008 convertedPattern.replace(firstQuotePos, (secondQuotePos - firstQuotePos) + 1, UnicodeString());
1009 }
1010
1011 if (convertedPattern.indexOf(LOW_H) != -1) {
1012 hourChar = LOW_H;
1013 } else if (convertedPattern.indexOf(CAP_K) != -1) {
1014 hourChar = CAP_K;
1015 } else if (convertedPattern.indexOf(LOW_K) != -1) {
1016 hourChar = LOW_K;
1017 }
1018
1019 if (convertedPattern.indexOf(LOW_B) != -1) {
1020 dayPeriodChar = LOW_B;
1021 } else if (convertedPattern.indexOf(CAP_B) != -1) {
1022 dayPeriodChar = CAP_B;
1023 } else if (dayPeriodChar == u'\0') {
1024 dayPeriodChar = LOW_A;
1025 }
1026 }
1027
1028 UnicodeString hourAndDayPeriod(hourChar);
1029 if (hourChar != CAP_H && hourChar != LOW_K) {
1030 int32_t newDayPeriodLength = 0;
1031 if (dayPeriodLength >= 5 || hourFieldLength >= 5) {
1032 newDayPeriodLength = 5;
1033 } else if (dayPeriodLength >= 3 || hourFieldLength >= 3) {
1034 newDayPeriodLength = 3;
1035 } else {
1036 newDayPeriodLength = 1;
1037 }
1038 for (int32_t i = 0; i < newDayPeriodLength; i++) {
1039 hourAndDayPeriod.append(dayPeriodChar);
1040 }
1041 }
1042 result.replace(hourFieldStart, hourFieldLength, hourAndDayPeriod);
1043 if (dayPeriodStart > hourFieldStart) {
1044 // before deleting the original day period field, adjust its position in case
1045 // we just changed the size of the hour field (and new day period field)
1046 dayPeriodStart += hourAndDayPeriod.length() - hourFieldLength;
1047 }
1048 result.remove(dayPeriodStart, dayPeriodLength);
1049 }
1050 return result;
1051 }
1052
1053
1054 void U_EXPORT2
getDateTimeSkeleton(const UnicodeString & skeleton,UnicodeString & dateSkeleton,UnicodeString & normalizedDateSkeleton,UnicodeString & timeSkeleton,UnicodeString & normalizedTimeSkeleton)1055 DateIntervalFormat::getDateTimeSkeleton(const UnicodeString& skeleton,
1056 UnicodeString& dateSkeleton,
1057 UnicodeString& normalizedDateSkeleton,
1058 UnicodeString& timeSkeleton,
1059 UnicodeString& normalizedTimeSkeleton) {
1060 // dateSkeleton follows the sequence of y*M*E*d*
1061 // timeSkeleton follows the sequence of hm*[v|z]?
1062 int32_t ECount = 0;
1063 int32_t dCount = 0;
1064 int32_t MCount = 0;
1065 int32_t yCount = 0;
1066 int32_t mCount = 0;
1067 int32_t vCount = 0;
1068 int32_t zCount = 0;
1069 char16_t hourChar = u'\0';
1070 int32_t i;
1071
1072 for (i = 0; i < skeleton.length(); ++i) {
1073 char16_t ch = skeleton[i];
1074 switch ( ch ) {
1075 case CAP_E:
1076 dateSkeleton.append(ch);
1077 ++ECount;
1078 break;
1079 case LOW_D:
1080 dateSkeleton.append(ch);
1081 ++dCount;
1082 break;
1083 case CAP_M:
1084 dateSkeleton.append(ch);
1085 ++MCount;
1086 break;
1087 case LOW_Y:
1088 dateSkeleton.append(ch);
1089 ++yCount;
1090 break;
1091 case CAP_G:
1092 case CAP_Y:
1093 case LOW_U:
1094 case CAP_Q:
1095 case LOW_Q:
1096 case CAP_L:
1097 case LOW_L:
1098 case CAP_W:
1099 case LOW_W:
1100 case CAP_D:
1101 case CAP_F:
1102 case LOW_G:
1103 case LOW_E:
1104 case LOW_C:
1105 case CAP_U:
1106 case LOW_R:
1107 normalizedDateSkeleton.append(ch);
1108 dateSkeleton.append(ch);
1109 break;
1110 case LOW_H:
1111 case CAP_H:
1112 case LOW_K:
1113 case CAP_K:
1114 timeSkeleton.append(ch);
1115 if (hourChar == u'\0') {
1116 hourChar = ch;
1117 }
1118 break;
1119 case LOW_M:
1120 timeSkeleton.append(ch);
1121 ++mCount;
1122 break;
1123 case LOW_Z:
1124 ++zCount;
1125 timeSkeleton.append(ch);
1126 break;
1127 case LOW_V:
1128 ++vCount;
1129 timeSkeleton.append(ch);
1130 break;
1131 case LOW_A:
1132 case CAP_V:
1133 case CAP_Z:
1134 case LOW_J:
1135 case LOW_S:
1136 case CAP_S:
1137 case CAP_A:
1138 case LOW_B:
1139 case CAP_B:
1140 timeSkeleton.append(ch);
1141 normalizedTimeSkeleton.append(ch);
1142 break;
1143 }
1144 }
1145
1146 /* generate normalized form for date*/
1147 if ( yCount != 0 ) {
1148 for (i = 0; i < yCount; ++i) {
1149 normalizedDateSkeleton.append(LOW_Y);
1150 }
1151 }
1152 if ( MCount != 0 ) {
1153 if ( MCount < 3 ) {
1154 normalizedDateSkeleton.append(CAP_M);
1155 } else {
1156 for ( int32_t j = 0; j < MCount && j < MAX_M_COUNT; ++j) {
1157 normalizedDateSkeleton.append(CAP_M);
1158 }
1159 }
1160 }
1161 if ( ECount != 0 ) {
1162 if ( ECount <= 3 ) {
1163 normalizedDateSkeleton.append(CAP_E);
1164 } else {
1165 for ( int32_t j = 0; j < ECount && j < MAX_E_COUNT; ++j ) {
1166 normalizedDateSkeleton.append(CAP_E);
1167 }
1168 }
1169 }
1170 if ( dCount != 0 ) {
1171 normalizedDateSkeleton.append(LOW_D);
1172 }
1173
1174 /* generate normalized form for time */
1175 if ( hourChar != u'\0' ) {
1176 normalizedTimeSkeleton.append(hourChar);
1177 }
1178 if ( mCount != 0 ) {
1179 normalizedTimeSkeleton.append(LOW_M);
1180 }
1181 if ( zCount != 0 ) {
1182 normalizedTimeSkeleton.append(LOW_Z);
1183 }
1184 if ( vCount != 0 ) {
1185 normalizedTimeSkeleton.append(LOW_V);
1186 }
1187 }
1188
1189
1190 /**
1191 * Generate date or time interval pattern from resource,
1192 * and set them into the interval pattern locale to this formatter.
1193 *
1194 * It needs to handle the following:
1195 * 1. need to adjust field width.
1196 * For example, the interval patterns saved in DateIntervalInfo
1197 * includes "dMMMy", but not "dMMMMy".
1198 * Need to get interval patterns for dMMMMy from dMMMy.
1199 * Another example, the interval patterns saved in DateIntervalInfo
1200 * includes "hmv", but not "hmz".
1201 * Need to get interval patterns for "hmz' from 'hmv'
1202 *
1203 * 2. there might be no pattern for 'y' differ for skeleton "Md",
1204 * in order to get interval patterns for 'y' differ,
1205 * need to look for it from skeleton 'yMd'
1206 *
1207 * @param dateSkeleton normalized date skeleton
1208 * @param timeSkeleton normalized time skeleton
1209 * @return whether the resource is found for the skeleton.
1210 * true if interval pattern found for the skeleton,
1211 * false otherwise.
1212 * @stable ICU 4.0
1213 */
1214 UBool
setSeparateDateTimePtn(const UnicodeString & dateSkeleton,const UnicodeString & timeSkeleton)1215 DateIntervalFormat::setSeparateDateTimePtn(
1216 const UnicodeString& dateSkeleton,
1217 const UnicodeString& timeSkeleton) {
1218 const UnicodeString* skeleton;
1219 // if both date and time skeleton present,
1220 // the final interval pattern might include time interval patterns
1221 // ( when, am_pm, hour, minute differ ),
1222 // but not date interval patterns ( when year, month, day differ ).
1223 // For year/month/day differ, it falls back to fall-back pattern.
1224 if ( timeSkeleton.length() != 0 ) {
1225 skeleton = &timeSkeleton;
1226 } else {
1227 skeleton = &dateSkeleton;
1228 }
1229
1230 /* interval patterns for skeleton "dMMMy" (but not "dMMMMy")
1231 * are defined in resource,
1232 * interval patterns for skeleton "dMMMMy" are calculated by
1233 * 1. get the best match skeleton for "dMMMMy", which is "dMMMy"
1234 * 2. get the interval patterns for "dMMMy",
1235 * 3. extend "MMM" to "MMMM" in above interval patterns for "dMMMMy"
1236 * getBestSkeleton() is step 1.
1237 */
1238 // best skeleton, and the difference information
1239 int8_t differenceInfo = 0;
1240 const UnicodeString* bestSkeleton = fInfo->getBestSkeleton(*skeleton,
1241 differenceInfo);
1242 /* best skeleton could be nullptr.
1243 For example: in "ca" resource file,
1244 interval format is defined as following
1245 intervalFormats{
1246 fallback{"{0} - {1}"}
1247 }
1248 there is no skeletons/interval patterns defined,
1249 and the best skeleton match could be nullptr
1250 */
1251 if ( bestSkeleton == nullptr ) {
1252 return false;
1253 }
1254
1255 // Set patterns for fallback use, need to do this
1256 // before returning if differenceInfo == -1
1257 UErrorCode status;
1258 if ( dateSkeleton.length() != 0) {
1259 status = U_ZERO_ERROR;
1260 fDatePattern = new UnicodeString(DateFormat::getBestPattern(
1261 fLocale, dateSkeleton, status));
1262 // no way to report OOM. :(
1263 }
1264 if ( timeSkeleton.length() != 0) {
1265 status = U_ZERO_ERROR;
1266 fTimePattern = new UnicodeString(DateFormat::getBestPattern(
1267 fLocale, timeSkeleton, status));
1268 // no way to report OOM. :(
1269 }
1270
1271 // difference:
1272 // 0 means the best matched skeleton is the same as input skeleton
1273 // 1 means the fields are the same, but field width are different
1274 // 2 means the only difference between fields are v/z,
1275 // -1 means there are other fields difference
1276 // (this will happen, for instance, if the supplied skeleton has seconds,
1277 // but no skeletons in the intervalFormats data do)
1278 if ( differenceInfo == -1 ) {
1279 // skeleton has different fields, not only v/z difference
1280 return false;
1281 }
1282
1283 if ( timeSkeleton.length() == 0 ) {
1284 UnicodeString extendedSkeleton;
1285 UnicodeString extendedBestSkeleton;
1286 // only has date skeleton
1287 setIntervalPattern(UCAL_DATE, skeleton, bestSkeleton, differenceInfo,
1288 &extendedSkeleton, &extendedBestSkeleton);
1289
1290 UBool extended = setIntervalPattern(UCAL_MONTH, skeleton, bestSkeleton,
1291 differenceInfo,
1292 &extendedSkeleton, &extendedBestSkeleton);
1293
1294 if ( extended ) {
1295 bestSkeleton = &extendedBestSkeleton;
1296 skeleton = &extendedSkeleton;
1297 }
1298 setIntervalPattern(UCAL_YEAR, skeleton, bestSkeleton, differenceInfo,
1299 &extendedSkeleton, &extendedBestSkeleton);
1300 setIntervalPattern(UCAL_ERA, skeleton, bestSkeleton, differenceInfo,
1301 &extendedSkeleton, &extendedBestSkeleton);
1302 } else {
1303 setIntervalPattern(UCAL_MINUTE, skeleton, bestSkeleton, differenceInfo);
1304 setIntervalPattern(UCAL_HOUR, skeleton, bestSkeleton, differenceInfo);
1305 setIntervalPattern(UCAL_AM_PM, skeleton, bestSkeleton, differenceInfo);
1306 }
1307 return true;
1308 }
1309
1310
1311
1312 void
setFallbackPattern(UCalendarDateFields field,const UnicodeString & skeleton,UErrorCode & status)1313 DateIntervalFormat::setFallbackPattern(UCalendarDateFields field,
1314 const UnicodeString& skeleton,
1315 UErrorCode& status) {
1316 if ( U_FAILURE(status) ) {
1317 return;
1318 }
1319 UnicodeString pattern = DateFormat::getBestPattern(
1320 fLocale, skeleton, status);
1321 if ( U_FAILURE(status) ) {
1322 return;
1323 }
1324 setPatternInfo(field, nullptr, &pattern, fInfo->getDefaultOrder());
1325 }
1326
1327
1328
1329
1330 void
setPatternInfo(UCalendarDateFields field,const UnicodeString * firstPart,const UnicodeString * secondPart,UBool laterDateFirst)1331 DateIntervalFormat::setPatternInfo(UCalendarDateFields field,
1332 const UnicodeString* firstPart,
1333 const UnicodeString* secondPart,
1334 UBool laterDateFirst) {
1335 // for fall back interval patterns,
1336 // the first part of the pattern is empty,
1337 // the second part of the pattern is the full-pattern
1338 // should be used in fall-back.
1339 UErrorCode status = U_ZERO_ERROR;
1340 // following should not set any wrong status.
1341 int32_t itvPtnIndex = DateIntervalInfo::calendarFieldToIntervalIndex(field,
1342 status);
1343 if ( U_FAILURE(status) ) {
1344 return;
1345 }
1346 PatternInfo& ptn = fIntervalPatterns[itvPtnIndex];
1347 if ( firstPart ) {
1348 ptn.firstPart = *firstPart;
1349 }
1350 if ( secondPart ) {
1351 ptn.secondPart = *secondPart;
1352 }
1353 ptn.laterDateFirst = laterDateFirst;
1354 }
1355
1356 void
setIntervalPattern(UCalendarDateFields field,const UnicodeString & intervalPattern)1357 DateIntervalFormat::setIntervalPattern(UCalendarDateFields field,
1358 const UnicodeString& intervalPattern) {
1359 UBool order = fInfo->getDefaultOrder();
1360 setIntervalPattern(field, intervalPattern, order);
1361 }
1362
1363
1364 void
setIntervalPattern(UCalendarDateFields field,const UnicodeString & intervalPattern,UBool laterDateFirst)1365 DateIntervalFormat::setIntervalPattern(UCalendarDateFields field,
1366 const UnicodeString& intervalPattern,
1367 UBool laterDateFirst) {
1368 const UnicodeString* pattern = &intervalPattern;
1369 UBool order = laterDateFirst;
1370 // check for "latestFirst:" or "earliestFirst:" prefix
1371 int8_t prefixLength = UPRV_LENGTHOF(gLaterFirstPrefix);
1372 int8_t earliestFirstLength = UPRV_LENGTHOF(gEarlierFirstPrefix);
1373 UnicodeString realPattern;
1374 if ( intervalPattern.startsWith(gLaterFirstPrefix, prefixLength) ) {
1375 order = true;
1376 intervalPattern.extract(prefixLength,
1377 intervalPattern.length() - prefixLength,
1378 realPattern);
1379 pattern = &realPattern;
1380 } else if ( intervalPattern.startsWith(gEarlierFirstPrefix,
1381 earliestFirstLength) ) {
1382 order = false;
1383 intervalPattern.extract(earliestFirstLength,
1384 intervalPattern.length() - earliestFirstLength,
1385 realPattern);
1386 pattern = &realPattern;
1387 }
1388
1389 int32_t splitPoint = splitPatternInto2Part(*pattern);
1390
1391 UnicodeString firstPart;
1392 UnicodeString secondPart;
1393 pattern->extract(0, splitPoint, firstPart);
1394 if ( splitPoint < pattern->length() ) {
1395 pattern->extract(splitPoint, pattern->length()-splitPoint, secondPart);
1396 }
1397 setPatternInfo(field, &firstPart, &secondPart, order);
1398 }
1399
1400
1401
1402
1403 /**
1404 * Generate interval pattern from existing resource
1405 *
1406 * It not only save the interval patterns,
1407 * but also return the extended skeleton and its best match skeleton.
1408 *
1409 * @param field largest different calendar field
1410 * @param skeleton skeleton
1411 * @param bestSkeleton the best match skeleton which has interval pattern
1412 * defined in resource
1413 * @param differenceInfo the difference between skeleton and best skeleton
1414 * 0 means the best matched skeleton is the same as input skeleton
1415 * 1 means the fields are the same, but field width are different
1416 * 2 means the only difference between fields are v/z,
1417 * -1 means there are other fields difference
1418 *
1419 * @param extendedSkeleton extended skeleton
1420 * @param extendedBestSkeleton extended best match skeleton
1421 * @return whether the interval pattern is found
1422 * through extending skeleton or not.
1423 * true if interval pattern is found by
1424 * extending skeleton, false otherwise.
1425 * @stable ICU 4.0
1426 */
1427 UBool
setIntervalPattern(UCalendarDateFields field,const UnicodeString * skeleton,const UnicodeString * bestSkeleton,int8_t differenceInfo,UnicodeString * extendedSkeleton,UnicodeString * extendedBestSkeleton)1428 DateIntervalFormat::setIntervalPattern(UCalendarDateFields field,
1429 const UnicodeString* skeleton,
1430 const UnicodeString* bestSkeleton,
1431 int8_t differenceInfo,
1432 UnicodeString* extendedSkeleton,
1433 UnicodeString* extendedBestSkeleton) {
1434 UErrorCode status = U_ZERO_ERROR;
1435 // following getIntervalPattern() should not generate error status
1436 UnicodeString pattern;
1437 fInfo->getIntervalPattern(*bestSkeleton, field, pattern, status);
1438 if ( pattern.isEmpty() ) {
1439 // single date
1440 if ( SimpleDateFormat::isFieldUnitIgnored(*bestSkeleton, field) ) {
1441 // do nothing, format will handle it
1442 return false;
1443 }
1444
1445 // for 24 hour system, interval patterns in resource file
1446 // might not include pattern when am_pm differ,
1447 // which should be the same as hour differ.
1448 // add it here for simplicity
1449 if ( field == UCAL_AM_PM ) {
1450 fInfo->getIntervalPattern(*bestSkeleton, UCAL_HOUR, pattern,status);
1451 if ( !pattern.isEmpty() ) {
1452 UBool suppressDayPeriodField = fSkeleton.indexOf(CAP_J) != -1;
1453 UnicodeString adjustIntervalPattern;
1454 adjustFieldWidth(*skeleton, *bestSkeleton, pattern, differenceInfo,
1455 suppressDayPeriodField, adjustIntervalPattern);
1456 setIntervalPattern(field, adjustIntervalPattern);
1457 }
1458 return false;
1459 }
1460 // else, looking for pattern when 'y' differ for 'dMMMM' skeleton,
1461 // first, get best match pattern "MMMd",
1462 // since there is no pattern for 'y' differs for skeleton 'MMMd',
1463 // need to look for it from skeleton 'yMMMd',
1464 // if found, adjust field width in interval pattern from
1465 // "MMM" to "MMMM".
1466 char16_t fieldLetter = fgCalendarFieldToPatternLetter[field];
1467 if ( extendedSkeleton ) {
1468 *extendedSkeleton = *skeleton;
1469 *extendedBestSkeleton = *bestSkeleton;
1470 extendedSkeleton->insert(0, fieldLetter);
1471 extendedBestSkeleton->insert(0, fieldLetter);
1472 // for example, looking for patterns when 'y' differ for
1473 // skeleton "MMMM".
1474 fInfo->getIntervalPattern(*extendedBestSkeleton,field,pattern,status);
1475 if ( pattern.isEmpty() && differenceInfo == 0 ) {
1476 // if there is no skeleton "yMMMM" defined,
1477 // look for the best match skeleton, for example: "yMMM"
1478 const UnicodeString* tmpBest = fInfo->getBestSkeleton(
1479 *extendedBestSkeleton, differenceInfo);
1480 if ( tmpBest != 0 && differenceInfo != -1 ) {
1481 fInfo->getIntervalPattern(*tmpBest, field, pattern, status);
1482 bestSkeleton = tmpBest;
1483 }
1484 }
1485 }
1486 }
1487 if ( !pattern.isEmpty() ) {
1488 UBool suppressDayPeriodField = fSkeleton.indexOf(CAP_J) != -1;
1489 if ( differenceInfo != 0 || suppressDayPeriodField) {
1490 UnicodeString adjustIntervalPattern;
1491 adjustFieldWidth(*skeleton, *bestSkeleton, pattern, differenceInfo,
1492 suppressDayPeriodField, adjustIntervalPattern);
1493 setIntervalPattern(field, adjustIntervalPattern);
1494 } else {
1495 setIntervalPattern(field, pattern);
1496 }
1497 if ( extendedSkeleton && !extendedSkeleton->isEmpty() ) {
1498 return true;
1499 }
1500 }
1501 return false;
1502 }
1503
1504
1505
1506 int32_t U_EXPORT2
splitPatternInto2Part(const UnicodeString & intervalPattern)1507 DateIntervalFormat::splitPatternInto2Part(const UnicodeString& intervalPattern) {
1508 UBool inQuote = false;
1509 char16_t prevCh = 0;
1510 int32_t count = 0;
1511
1512 /* repeatedPattern used to record whether a pattern has already seen.
1513 It is a pattern applies to first calendar if it is first time seen,
1514 otherwise, it is a pattern applies to the second calendar
1515 */
1516 UBool patternRepeated[] =
1517 {
1518 // A B C D E F G H I J K L M N O
1519 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1520 // P Q R S T U V W X Y Z
1521 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1522 // a b c d e f g h i j k l m n o
1523 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1524 // p q r s t u v w x y z
1525 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
1526 };
1527
1528 int8_t PATTERN_CHAR_BASE = 0x41;
1529
1530 /* loop through the pattern string character by character looking for
1531 * the first repeated pattern letter, which breaks the interval pattern
1532 * into 2 parts.
1533 */
1534 int32_t i;
1535 UBool foundRepetition = false;
1536 for (i = 0; i < intervalPattern.length(); ++i) {
1537 char16_t ch = intervalPattern.charAt(i);
1538
1539 if (ch != prevCh && count > 0) {
1540 // check the repeativeness of pattern letter
1541 UBool repeated = patternRepeated[(int)(prevCh - PATTERN_CHAR_BASE)];
1542 if ( repeated == false ) {
1543 patternRepeated[prevCh - PATTERN_CHAR_BASE] = true;
1544 } else {
1545 foundRepetition = true;
1546 break;
1547 }
1548 count = 0;
1549 }
1550 if (ch == 0x0027 /*'*/) {
1551 // Consecutive single quotes are a single quote literal,
1552 // either outside of quotes or between quotes
1553 if ((i+1) < intervalPattern.length() &&
1554 intervalPattern.charAt(i+1) == 0x0027 /*'*/) {
1555 ++i;
1556 } else {
1557 inQuote = ! inQuote;
1558 }
1559 }
1560 else if (!inQuote && ((ch >= 0x0061 /*'a'*/ && ch <= 0x007A /*'z'*/)
1561 || (ch >= 0x0041 /*'A'*/ && ch <= 0x005A /*'Z'*/))) {
1562 // ch is a date-time pattern character
1563 prevCh = ch;
1564 ++count;
1565 }
1566 }
1567 // check last pattern char, distinguish
1568 // "dd MM" ( no repetition ),
1569 // "d-d"(last char repeated ), and
1570 // "d-d MM" ( repetition found )
1571 if ( count > 0 && foundRepetition == false ) {
1572 if ( patternRepeated[(int)(prevCh - PATTERN_CHAR_BASE)] == false ) {
1573 count = 0;
1574 }
1575 }
1576 return (i - count);
1577 }
1578
1579 // 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) const1580 void DateIntervalFormat::fallbackFormatRange(
1581 Calendar& fromCalendar,
1582 Calendar& toCalendar,
1583 UnicodeString& appendTo,
1584 int8_t& firstIndex,
1585 FieldPositionHandler& fphandler,
1586 UErrorCode& status) const {
1587 UnicodeString fallbackPattern;
1588 fInfo->getFallbackIntervalPattern(fallbackPattern);
1589 SimpleFormatter sf(fallbackPattern, 2, 2, status);
1590 if (U_FAILURE(status)) {
1591 return;
1592 }
1593 int32_t offsets[2];
1594 UnicodeString patternBody = sf.getTextWithNoArguments(offsets, 2);
1595
1596 UErrorCode tempStatus = U_ZERO_ERROR; // for setContext, ignored
1597 // TODO(ICU-20406): Use SimpleFormatter Iterator interface when available.
1598 if (offsets[0] < offsets[1]) {
1599 firstIndex = 0;
1600 appendTo.append(patternBody.tempSubStringBetween(0, offsets[0]));
1601 fDateFormat->_format(fromCalendar, appendTo, fphandler, status);
1602 appendTo.append(patternBody.tempSubStringBetween(offsets[0], offsets[1]));
1603 // No capitalization for second part of interval
1604 fDateFormat->setContext(UDISPCTX_CAPITALIZATION_NONE, tempStatus);
1605 fDateFormat->_format(toCalendar, appendTo, fphandler, status);
1606 appendTo.append(patternBody.tempSubStringBetween(offsets[1]));
1607 } else {
1608 firstIndex = 1;
1609 appendTo.append(patternBody.tempSubStringBetween(0, offsets[1]));
1610 fDateFormat->_format(toCalendar, appendTo, fphandler, status);
1611 appendTo.append(patternBody.tempSubStringBetween(offsets[1], offsets[0]));
1612 // No capitalization for second part of interval
1613 fDateFormat->setContext(UDISPCTX_CAPITALIZATION_NONE, tempStatus);
1614 fDateFormat->_format(fromCalendar, appendTo, fphandler, status);
1615 appendTo.append(patternBody.tempSubStringBetween(offsets[0]));
1616 }
1617 }
1618
1619 // The following is only called from formatImpl, i.e. within the gFormatterMutex lock
1620 UnicodeString&
fallbackFormat(Calendar & fromCalendar,Calendar & toCalendar,UBool fromToOnSameDay,UnicodeString & appendTo,int8_t & firstIndex,FieldPositionHandler & fphandler,UErrorCode & status) const1621 DateIntervalFormat::fallbackFormat(Calendar& fromCalendar,
1622 Calendar& toCalendar,
1623 UBool fromToOnSameDay, // new
1624 UnicodeString& appendTo,
1625 int8_t& firstIndex,
1626 FieldPositionHandler& fphandler,
1627 UErrorCode& status) const {
1628 if ( U_FAILURE(status) ) {
1629 return appendTo;
1630 }
1631
1632 UBool formatDatePlusTimeRange = (fromToOnSameDay && fDatePattern && fTimePattern);
1633 if (formatDatePlusTimeRange) {
1634 SimpleFormatter sf(*fDateTimeFormat, 2, 2, status);
1635 if (U_FAILURE(status)) {
1636 return appendTo;
1637 }
1638 int32_t offsets[2];
1639 UnicodeString patternBody = sf.getTextWithNoArguments(offsets, 2);
1640
1641 UnicodeString fullPattern; // for saving the pattern in fDateFormat
1642 fDateFormat->toPattern(fullPattern); // save current pattern, restore later
1643
1644 UErrorCode tempStatus = U_ZERO_ERROR; // for setContext, ignored
1645 // {0} is time range
1646 // {1} is single date portion
1647 // TODO(ICU-20406): Use SimpleFormatter Iterator interface when available.
1648 if (offsets[0] < offsets[1]) {
1649 appendTo.append(patternBody.tempSubStringBetween(0, offsets[0]));
1650 fDateFormat->applyPattern(*fTimePattern);
1651 fallbackFormatRange(fromCalendar, toCalendar, appendTo, firstIndex, fphandler, status);
1652 appendTo.append(patternBody.tempSubStringBetween(offsets[0], offsets[1]));
1653 fDateFormat->applyPattern(*fDatePattern);
1654 // No capitalization for second portion
1655 fDateFormat->setContext(UDISPCTX_CAPITALIZATION_NONE, tempStatus);
1656 fDateFormat->_format(fromCalendar, appendTo, fphandler, status);
1657 appendTo.append(patternBody.tempSubStringBetween(offsets[1]));
1658 } else {
1659 appendTo.append(patternBody.tempSubStringBetween(0, offsets[1]));
1660 fDateFormat->applyPattern(*fDatePattern);
1661 fDateFormat->_format(fromCalendar, appendTo, fphandler, status);
1662 appendTo.append(patternBody.tempSubStringBetween(offsets[1], offsets[0]));
1663 fDateFormat->applyPattern(*fTimePattern);
1664 // No capitalization for second portion
1665 fDateFormat->setContext(UDISPCTX_CAPITALIZATION_NONE, tempStatus);
1666 fallbackFormatRange(fromCalendar, toCalendar, appendTo, firstIndex, fphandler, status);
1667 appendTo.append(patternBody.tempSubStringBetween(offsets[0]));
1668 }
1669
1670 // restore full pattern
1671 fDateFormat->applyPattern(fullPattern);
1672 } else {
1673 fallbackFormatRange(fromCalendar, toCalendar, appendTo, firstIndex, fphandler, status);
1674 }
1675 return appendTo;
1676 }
1677
1678
1679
1680
1681 UBool U_EXPORT2
fieldExistsInSkeleton(UCalendarDateFields field,const UnicodeString & skeleton)1682 DateIntervalFormat::fieldExistsInSkeleton(UCalendarDateFields field,
1683 const UnicodeString& skeleton)
1684 {
1685 const char16_t fieldChar = fgCalendarFieldToPatternLetter[field];
1686 return ( (skeleton.indexOf(fieldChar) == -1)?false:true ) ;
1687 }
1688
1689
1690
1691 void U_EXPORT2
adjustFieldWidth(const UnicodeString & inputSkeleton,const UnicodeString & bestMatchSkeleton,const UnicodeString & bestIntervalPattern,int8_t differenceInfo,UBool suppressDayPeriodField,UnicodeString & adjustedPtn)1692 DateIntervalFormat::adjustFieldWidth(const UnicodeString& inputSkeleton,
1693 const UnicodeString& bestMatchSkeleton,
1694 const UnicodeString& bestIntervalPattern,
1695 int8_t differenceInfo,
1696 UBool suppressDayPeriodField,
1697 UnicodeString& adjustedPtn) {
1698 adjustedPtn = bestIntervalPattern;
1699 int32_t inputSkeletonFieldWidth[] =
1700 {
1701 // A B C D E F G H I J K L M N O
1702 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1703 // P Q R S T U V W X Y Z
1704 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1705 // a b c d e f g h i j k l m n o
1706 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1707 // p q r s t u v w x y z
1708 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
1709 };
1710
1711 int32_t bestMatchSkeletonFieldWidth[] =
1712 {
1713 // A B C D E F G H I J K L M N O
1714 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1715 // P Q R S T U V W X Y Z
1716 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1717 // a b c d e f g h i j k l m n o
1718 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1719 // p q r s t u v w x y z
1720 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
1721 };
1722
1723 const int8_t PATTERN_CHAR_BASE = 0x41;
1724
1725 DateIntervalInfo::parseSkeleton(inputSkeleton, inputSkeletonFieldWidth);
1726 DateIntervalInfo::parseSkeleton(bestMatchSkeleton, bestMatchSkeletonFieldWidth);
1727 if (suppressDayPeriodField) {
1728 // remove the 'a' and any NBSP/NNBSP on one side of it
1729 findReplaceInPattern(adjustedPtn, UnicodeString(u"\u00A0a",-1), UnicodeString());
1730 findReplaceInPattern(adjustedPtn, UnicodeString(u"\u202Fa",-1), UnicodeString());
1731 findReplaceInPattern(adjustedPtn, UnicodeString(u"a\u00A0",-1), UnicodeString());
1732 findReplaceInPattern(adjustedPtn, UnicodeString(u"a\u202F",-1), UnicodeString());
1733 findReplaceInPattern(adjustedPtn, UnicodeString(LOW_A), UnicodeString());
1734 // adjust interior double spaces, remove exterior whitespace
1735 findReplaceInPattern(adjustedPtn, UnicodeString(" "), UnicodeString(" "));
1736 adjustedPtn.trim();
1737 }
1738 if ( differenceInfo == 2 ) {
1739 if (inputSkeleton.indexOf(LOW_Z) != -1) {
1740 findReplaceInPattern(adjustedPtn, UnicodeString(LOW_V), UnicodeString(LOW_Z));
1741 }
1742 if (inputSkeleton.indexOf(CAP_K) != -1) {
1743 findReplaceInPattern(adjustedPtn, UnicodeString(LOW_H), UnicodeString(CAP_K));
1744 }
1745 if (inputSkeleton.indexOf(LOW_K) != -1) {
1746 findReplaceInPattern(adjustedPtn, UnicodeString(CAP_H), UnicodeString(LOW_K));
1747 }
1748 if (inputSkeleton.indexOf(LOW_B) != -1) {
1749 findReplaceInPattern(adjustedPtn, UnicodeString(LOW_A), UnicodeString(LOW_B));
1750 }
1751 }
1752 if (adjustedPtn.indexOf(LOW_A) != -1 && bestMatchSkeletonFieldWidth[LOW_A - PATTERN_CHAR_BASE] == 0) {
1753 bestMatchSkeletonFieldWidth[LOW_A - PATTERN_CHAR_BASE] = 1;
1754 }
1755 if (adjustedPtn.indexOf(LOW_B) != -1 && bestMatchSkeletonFieldWidth[LOW_B - PATTERN_CHAR_BASE] == 0) {
1756 bestMatchSkeletonFieldWidth[LOW_B - PATTERN_CHAR_BASE] = 1;
1757 }
1758
1759 UBool inQuote = false;
1760 char16_t prevCh = 0;
1761 int32_t count = 0;
1762
1763 // loop through the pattern string character by character
1764 int32_t adjustedPtnLength = adjustedPtn.length();
1765 int32_t i;
1766 for (i = 0; i < adjustedPtnLength; ++i) {
1767 char16_t ch = adjustedPtn.charAt(i);
1768 if (ch != prevCh && count > 0) {
1769 // check the repeativeness of pattern letter
1770 char16_t skeletonChar = prevCh;
1771 if ( skeletonChar == CAP_L ) {
1772 // there is no "L" (always be "M") in skeleton,
1773 // but there is "L" in pattern.
1774 // for skeleton "M+", the pattern might be "...L..."
1775 skeletonChar = CAP_M;
1776 }
1777 int32_t fieldCount = bestMatchSkeletonFieldWidth[(int)(skeletonChar - PATTERN_CHAR_BASE)];
1778 int32_t inputFieldCount = inputSkeletonFieldWidth[(int)(skeletonChar - PATTERN_CHAR_BASE)];
1779 if ( fieldCount == count && inputFieldCount > fieldCount ) {
1780 count = inputFieldCount - fieldCount;
1781 int32_t j;
1782 for ( j = 0; j < count; ++j ) {
1783 adjustedPtn.insert(i, prevCh);
1784 }
1785 i += count;
1786 adjustedPtnLength += count;
1787 }
1788 count = 0;
1789 }
1790 if (ch == 0x0027 /*'*/) {
1791 // Consecutive single quotes are a single quote literal,
1792 // either outside of quotes or between quotes
1793 if ((i+1) < adjustedPtn.length() && adjustedPtn.charAt(i+1) == 0x0027 /* ' */) {
1794 ++i;
1795 } else {
1796 inQuote = ! inQuote;
1797 }
1798 }
1799 else if ( ! inQuote && ((ch >= 0x0061 /*'a'*/ && ch <= 0x007A /*'z'*/)
1800 || (ch >= 0x0041 /*'A'*/ && ch <= 0x005A /*'Z'*/))) {
1801 // ch is a date-time pattern character
1802 prevCh = ch;
1803 ++count;
1804 }
1805 }
1806 if ( count > 0 ) {
1807 // last item
1808 // check the repeativeness of pattern letter
1809 char16_t skeletonChar = prevCh;
1810 if ( skeletonChar == CAP_L ) {
1811 // there is no "L" (always be "M") in skeleton,
1812 // but there is "L" in pattern.
1813 // for skeleton "M+", the pattern might be "...L..."
1814 skeletonChar = CAP_M;
1815 }
1816 int32_t fieldCount = bestMatchSkeletonFieldWidth[(int)(skeletonChar - PATTERN_CHAR_BASE)];
1817 int32_t inputFieldCount = inputSkeletonFieldWidth[(int)(skeletonChar - PATTERN_CHAR_BASE)];
1818 if ( fieldCount == count && inputFieldCount > fieldCount ) {
1819 count = inputFieldCount - fieldCount;
1820 int32_t j;
1821 for ( j = 0; j < count; ++j ) {
1822 adjustedPtn.append(prevCh);
1823 }
1824 }
1825 }
1826 }
1827
1828 void
findReplaceInPattern(UnicodeString & targetString,const UnicodeString & strToReplace,const UnicodeString & strToReplaceWith)1829 DateIntervalFormat::findReplaceInPattern(UnicodeString& targetString,
1830 const UnicodeString& strToReplace,
1831 const UnicodeString& strToReplaceWith) {
1832 int32_t firstQuoteIndex = targetString.indexOf(u'\'');
1833 if (firstQuoteIndex == -1) {
1834 targetString.findAndReplace(strToReplace, strToReplaceWith);
1835 } else {
1836 UnicodeString result;
1837 UnicodeString source = targetString;
1838
1839 while (firstQuoteIndex >= 0) {
1840 int32_t secondQuoteIndex = source.indexOf(u'\'', firstQuoteIndex + 1);
1841 if (secondQuoteIndex == -1) {
1842 secondQuoteIndex = source.length() - 1;
1843 }
1844
1845 UnicodeString unquotedText(source, 0, firstQuoteIndex);
1846 UnicodeString quotedText(source, firstQuoteIndex, secondQuoteIndex - firstQuoteIndex + 1);
1847
1848 unquotedText.findAndReplace(strToReplace, strToReplaceWith);
1849 result += unquotedText;
1850 result += quotedText;
1851
1852 source.remove(0, secondQuoteIndex + 1);
1853 firstQuoteIndex = source.indexOf(u'\'');
1854 }
1855 source.findAndReplace(strToReplace, strToReplaceWith);
1856 result += source;
1857 targetString = result;
1858 }
1859 }
1860
1861
1862
1863 void
concatSingleDate2TimeInterval(UnicodeString & format,const UnicodeString & datePattern,UCalendarDateFields field,UErrorCode & status)1864 DateIntervalFormat::concatSingleDate2TimeInterval(UnicodeString& format,
1865 const UnicodeString& datePattern,
1866 UCalendarDateFields field,
1867 UErrorCode& status) {
1868 // following should not set wrong status
1869 int32_t itvPtnIndex = DateIntervalInfo::calendarFieldToIntervalIndex(field,
1870 status);
1871 if ( U_FAILURE(status) ) {
1872 return;
1873 }
1874 PatternInfo& timeItvPtnInfo = fIntervalPatterns[itvPtnIndex];
1875 if ( !timeItvPtnInfo.firstPart.isEmpty() ) {
1876 UnicodeString timeIntervalPattern(timeItvPtnInfo.firstPart);
1877 timeIntervalPattern.append(timeItvPtnInfo.secondPart);
1878 UnicodeString combinedPattern;
1879 SimpleFormatter(format, 2, 2, status).
1880 format(timeIntervalPattern, datePattern, combinedPattern, status);
1881 if ( U_FAILURE(status) ) {
1882 return;
1883 }
1884 setIntervalPattern(field, combinedPattern, timeItvPtnInfo.laterDateFirst);
1885 }
1886 // else: fall back
1887 // it should not happen if the interval format defined is valid
1888 }
1889
1890
1891
1892 const char16_t
1893 DateIntervalFormat::fgCalendarFieldToPatternLetter[] =
1894 {
1895 /*GyM*/ CAP_G, LOW_Y, CAP_M,
1896 /*wWd*/ LOW_W, CAP_W, LOW_D,
1897 /*DEF*/ CAP_D, CAP_E, CAP_F,
1898 /*ahH*/ LOW_A, LOW_H, CAP_H,
1899 /*msS*/ LOW_M, LOW_S, CAP_S, // MINUTE, SECOND, MILLISECOND
1900 /*z.Y*/ LOW_Z, SPACE, CAP_Y, // ZONE_OFFSET, DST_OFFSET, YEAR_WOY,
1901 /*eug*/ LOW_E, LOW_U, LOW_G, // DOW_LOCAL, EXTENDED_YEAR, JULIAN_DAY,
1902 /*A..*/ CAP_A, SPACE, SPACE, // MILLISECONDS_IN_DAY, IS_LEAP_MONTH, FIELD_COUNT
1903 };
1904
1905
1906
1907 U_NAMESPACE_END
1908
1909 #endif
1910