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