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