1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "base/i18n/time_formatting.h"
6
7 #include <stddef.h>
8
9 #include <memory>
10
11 #include "base/i18n/unicodestring.h"
12 #include "base/logging.h"
13 #include "base/strings/utf_string_conversions.h"
14 #include "base/time/time.h"
15 #include "third_party/icu/source/common/unicode/utypes.h"
16 #include "third_party/icu/source/i18n/unicode/datefmt.h"
17 #include "third_party/icu/source/i18n/unicode/dtitvfmt.h"
18 #include "third_party/icu/source/i18n/unicode/dtptngen.h"
19 #include "third_party/icu/source/i18n/unicode/fmtable.h"
20 #include "third_party/icu/source/i18n/unicode/measfmt.h"
21 #include "third_party/icu/source/i18n/unicode/smpdtfmt.h"
22
23 namespace base {
24 namespace {
25
TimeFormat(const icu::DateFormat * formatter,const Time & time)26 string16 TimeFormat(const icu::DateFormat* formatter,
27 const Time& time) {
28 DCHECK(formatter);
29 icu::UnicodeString date_string;
30
31 formatter->format(static_cast<UDate>(time.ToDoubleT() * 1000), date_string);
32 return i18n::UnicodeStringToString16(date_string);
33 }
34
TimeFormatWithoutAmPm(const icu::DateFormat * formatter,const Time & time)35 string16 TimeFormatWithoutAmPm(const icu::DateFormat* formatter,
36 const Time& time) {
37 DCHECK(formatter);
38 icu::UnicodeString time_string;
39
40 icu::FieldPosition ampm_field(icu::DateFormat::kAmPmField);
41 formatter->format(
42 static_cast<UDate>(time.ToDoubleT() * 1000), time_string, ampm_field);
43 int ampm_length = ampm_field.getEndIndex() - ampm_field.getBeginIndex();
44 if (ampm_length) {
45 int begin = ampm_field.getBeginIndex();
46 // Doesn't include any spacing before the field.
47 if (begin)
48 begin--;
49 time_string.removeBetween(begin, ampm_field.getEndIndex());
50 }
51 return i18n::UnicodeStringToString16(time_string);
52 }
53
CreateSimpleDateFormatter(const char * pattern)54 icu::SimpleDateFormat CreateSimpleDateFormatter(const char* pattern) {
55 // Generate a locale-dependent format pattern. The generator will take
56 // care of locale-dependent formatting issues like which separator to
57 // use (some locales use '.' instead of ':'), and where to put the am/pm
58 // marker.
59 UErrorCode status = U_ZERO_ERROR;
60 std::unique_ptr<icu::DateTimePatternGenerator> generator(
61 icu::DateTimePatternGenerator::createInstance(status));
62 DCHECK(U_SUCCESS(status));
63 icu::UnicodeString generated_pattern =
64 generator->getBestPattern(icu::UnicodeString(pattern), status);
65 DCHECK(U_SUCCESS(status));
66
67 // Then, format the time using the generated pattern.
68 icu::SimpleDateFormat formatter(generated_pattern, status);
69 DCHECK(U_SUCCESS(status));
70
71 return formatter;
72 }
73
DurationWidthToMeasureWidth(DurationFormatWidth width)74 UMeasureFormatWidth DurationWidthToMeasureWidth(DurationFormatWidth width) {
75 switch (width) {
76 case DURATION_WIDTH_WIDE: return UMEASFMT_WIDTH_WIDE;
77 case DURATION_WIDTH_SHORT: return UMEASFMT_WIDTH_SHORT;
78 case DURATION_WIDTH_NARROW: return UMEASFMT_WIDTH_NARROW;
79 case DURATION_WIDTH_NUMERIC: return UMEASFMT_WIDTH_NUMERIC;
80 }
81 NOTREACHED();
82 return UMEASFMT_WIDTH_COUNT;
83 }
84
DateFormatToString(DateFormat format)85 const char* DateFormatToString(DateFormat format) {
86 switch (format) {
87 case DATE_FORMAT_YEAR_MONTH:
88 return UDAT_YEAR_MONTH;
89 case DATE_FORMAT_MONTH_WEEKDAY_DAY:
90 return UDAT_MONTH_WEEKDAY_DAY;
91 }
92 NOTREACHED();
93 return UDAT_YEAR_MONTH_DAY;
94 }
95
96 } // namespace
97
TimeFormatTimeOfDay(const Time & time)98 string16 TimeFormatTimeOfDay(const Time& time) {
99 // We can omit the locale parameter because the default should match
100 // Chrome's application locale.
101 std::unique_ptr<icu::DateFormat> formatter(
102 icu::DateFormat::createTimeInstance(icu::DateFormat::kShort));
103 return TimeFormat(formatter.get(), time);
104 }
105
TimeFormatTimeOfDayWithMilliseconds(const Time & time)106 string16 TimeFormatTimeOfDayWithMilliseconds(const Time& time) {
107 icu::SimpleDateFormat formatter = CreateSimpleDateFormatter("HmsSSS");
108 return TimeFormatWithoutAmPm(&formatter, time);
109 }
110
TimeFormatTimeOfDayWithHourClockType(const Time & time,HourClockType type,AmPmClockType ampm)111 string16 TimeFormatTimeOfDayWithHourClockType(const Time& time,
112 HourClockType type,
113 AmPmClockType ampm) {
114 // Just redirect to the normal function if the default type matches the
115 // given type.
116 HourClockType default_type = GetHourClockType();
117 if (default_type == type && (type == k24HourClock || ampm == kKeepAmPm)) {
118 return TimeFormatTimeOfDay(time);
119 }
120
121 const char* base_pattern = (type == k12HourClock ? "ahm" : "Hm");
122 icu::SimpleDateFormat formatter = CreateSimpleDateFormatter(base_pattern);
123
124 if (ampm == kKeepAmPm) {
125 return TimeFormat(&formatter, time);
126 } else {
127 return TimeFormatWithoutAmPm(&formatter, time);
128 }
129 }
130
TimeFormatShortDate(const Time & time)131 string16 TimeFormatShortDate(const Time& time) {
132 std::unique_ptr<icu::DateFormat> formatter(
133 icu::DateFormat::createDateInstance(icu::DateFormat::kMedium));
134 return TimeFormat(formatter.get(), time);
135 }
136
TimeFormatShortDateNumeric(const Time & time)137 string16 TimeFormatShortDateNumeric(const Time& time) {
138 std::unique_ptr<icu::DateFormat> formatter(
139 icu::DateFormat::createDateInstance(icu::DateFormat::kShort));
140 return TimeFormat(formatter.get(), time);
141 }
142
TimeFormatShortDateAndTime(const Time & time)143 string16 TimeFormatShortDateAndTime(const Time& time) {
144 std::unique_ptr<icu::DateFormat> formatter(
145 icu::DateFormat::createDateTimeInstance(icu::DateFormat::kShort));
146 return TimeFormat(formatter.get(), time);
147 }
148
TimeFormatShortDateAndTimeWithTimeZone(const Time & time)149 string16 TimeFormatShortDateAndTimeWithTimeZone(const Time& time) {
150 std::unique_ptr<icu::DateFormat> formatter(
151 icu::DateFormat::createDateTimeInstance(icu::DateFormat::kShort,
152 icu::DateFormat::kLong));
153 return TimeFormat(formatter.get(), time);
154 }
155
TimeFormatMonthAndYear(const Time & time)156 string16 TimeFormatMonthAndYear(const Time& time) {
157 icu::SimpleDateFormat formatter =
158 CreateSimpleDateFormatter(DateFormatToString(DATE_FORMAT_YEAR_MONTH));
159 return TimeFormat(&formatter, time);
160 }
161
TimeFormatFriendlyDateAndTime(const Time & time)162 string16 TimeFormatFriendlyDateAndTime(const Time& time) {
163 std::unique_ptr<icu::DateFormat> formatter(
164 icu::DateFormat::createDateTimeInstance(icu::DateFormat::kFull));
165 return TimeFormat(formatter.get(), time);
166 }
167
TimeFormatFriendlyDate(const Time & time)168 string16 TimeFormatFriendlyDate(const Time& time) {
169 std::unique_ptr<icu::DateFormat> formatter(
170 icu::DateFormat::createDateInstance(icu::DateFormat::kFull));
171 return TimeFormat(formatter.get(), time);
172 }
173
TimeFormatWithPattern(const Time & time,const char * pattern)174 string16 TimeFormatWithPattern(const Time& time, const char* pattern) {
175 icu::SimpleDateFormat formatter = CreateSimpleDateFormatter(pattern);
176 return TimeFormat(&formatter, time);
177 }
178
TimeDurationFormat(const TimeDelta time,const DurationFormatWidth width,string16 * out)179 bool TimeDurationFormat(const TimeDelta time,
180 const DurationFormatWidth width,
181 string16* out) {
182 DCHECK(out);
183 UErrorCode status = U_ZERO_ERROR;
184 const int total_minutes = static_cast<int>(time.InSecondsF() / 60 + 0.5);
185 const int hours = total_minutes / 60;
186 const int minutes = total_minutes % 60;
187 UMeasureFormatWidth u_width = DurationWidthToMeasureWidth(width);
188
189 // TODO(derat): Delete the |status| checks and LOG(ERROR) calls throughout
190 // this function once the cause of http://crbug.com/677043 is tracked down.
191 const icu::Measure measures[] = {
192 icu::Measure(hours, icu::MeasureUnit::createHour(status), status),
193 icu::Measure(minutes, icu::MeasureUnit::createMinute(status), status)};
194 if (U_FAILURE(status)) {
195 LOG(ERROR) << "Creating MeasureUnit or Measure for " << hours << "h"
196 << minutes << "m failed: " << u_errorName(status);
197 return false;
198 }
199
200 icu::MeasureFormat measure_format(icu::Locale::getDefault(), u_width, status);
201 if (U_FAILURE(status)) {
202 LOG(ERROR) << "Creating MeasureFormat for "
203 << icu::Locale::getDefault().getName()
204 << " failed: " << u_errorName(status);
205 return false;
206 }
207
208 icu::UnicodeString formatted;
209 icu::FieldPosition ignore(icu::FieldPosition::DONT_CARE);
210 measure_format.formatMeasures(measures, 2, formatted, ignore, status);
211 if (U_FAILURE(status)) {
212 LOG(ERROR) << "formatMeasures failed: " << u_errorName(status);
213 return false;
214 }
215
216 *out = i18n::UnicodeStringToString16(formatted);
217 return true;
218 }
219
TimeDurationFormatWithSeconds(const TimeDelta time,const DurationFormatWidth width,string16 * out)220 bool TimeDurationFormatWithSeconds(const TimeDelta time,
221 const DurationFormatWidth width,
222 string16* out) {
223 DCHECK(out);
224 UErrorCode status = U_ZERO_ERROR;
225 const int64_t total_seconds = static_cast<int>(time.InSecondsF() + 0.5);
226 const int hours = total_seconds / 3600;
227 const int minutes = (total_seconds - hours * 3600) / 60;
228 const int seconds = total_seconds % 60;
229 UMeasureFormatWidth u_width = DurationWidthToMeasureWidth(width);
230
231 const icu::Measure measures[] = {
232 icu::Measure(hours, icu::MeasureUnit::createHour(status), status),
233 icu::Measure(minutes, icu::MeasureUnit::createMinute(status), status),
234 icu::Measure(seconds, icu::MeasureUnit::createSecond(status), status)};
235 icu::MeasureFormat measure_format(icu::Locale::getDefault(), u_width, status);
236 icu::UnicodeString formatted;
237 icu::FieldPosition ignore(icu::FieldPosition::DONT_CARE);
238 measure_format.formatMeasures(measures, 3, formatted, ignore, status);
239 *out = i18n::UnicodeStringToString16(formatted);
240 return U_SUCCESS(status) == TRUE;
241 }
242
DateIntervalFormat(const Time & begin_time,const Time & end_time,DateFormat format)243 string16 DateIntervalFormat(const Time& begin_time,
244 const Time& end_time,
245 DateFormat format) {
246 UErrorCode status = U_ZERO_ERROR;
247
248 std::unique_ptr<icu::DateIntervalFormat> formatter(
249 icu::DateIntervalFormat::createInstance(DateFormatToString(format),
250 status));
251
252 icu::FieldPosition pos = 0;
253 UDate start_date = static_cast<UDate>(begin_time.ToDoubleT() * 1000);
254 UDate end_date = static_cast<UDate>(end_time.ToDoubleT() * 1000);
255 icu::DateInterval interval(start_date, end_date);
256 icu::UnicodeString formatted;
257 formatter->format(&interval, formatted, pos, status);
258 return i18n::UnicodeStringToString16(formatted);
259 }
260
GetHourClockType()261 HourClockType GetHourClockType() {
262 // TODO(satorux,jshin): Rework this with ures_getByKeyWithFallback()
263 // once it becomes public. The short time format can be found at
264 // "calendar/gregorian/DateTimePatterns/3" in the resources.
265 std::unique_ptr<icu::SimpleDateFormat> formatter(
266 static_cast<icu::SimpleDateFormat*>(
267 icu::DateFormat::createTimeInstance(icu::DateFormat::kShort)));
268 // Retrieve the short time format.
269 icu::UnicodeString pattern_unicode;
270 formatter->toPattern(pattern_unicode);
271
272 // Determine what hour clock type the current locale uses, by checking
273 // "a" (am/pm marker) in the short time format. This is reliable as "a"
274 // is used by all of 12-hour clock formats, but not any of 24-hour clock
275 // formats, as shown below.
276 //
277 // % grep -A4 DateTimePatterns third_party/icu/source/data/locales/*.txt |
278 // grep -B1 -- -- |grep -v -- '--' |
279 // perl -nle 'print $1 if /^\S+\s+"(.*)"/' |sort -u
280 //
281 // H.mm
282 // H:mm
283 // HH.mm
284 // HH:mm
285 // a h:mm
286 // ah:mm
287 // ahh:mm
288 // h-mm a
289 // h:mm a
290 // hh:mm a
291 //
292 // See http://userguide.icu-project.org/formatparse/datetime for details
293 // about the date/time format syntax.
294 if (pattern_unicode.indexOf('a') == -1) {
295 return k24HourClock;
296 } else {
297 return k12HourClock;
298 }
299 }
300
301 } // namespace base
302