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