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