blob: b00a9385eec8173f0e91f173ec85d3eeb3bfa3dd [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.text.format;
18
Mathew Inwoodefeab842018-08-14 15:21:30 +010019import android.annotation.UnsupportedAppUsage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import android.content.Context;
21import android.content.res.Configuration;
22import android.content.res.Resources;
Roozbeh Pournaderc6bffbf2016-12-13 13:58:56 -080023import android.icu.text.MeasureFormat;
24import android.icu.text.MeasureFormat.FormatWidth;
25import android.icu.util.Measure;
26import android.icu.util.MeasureUnit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027
Aurimas Liutikas4037d512016-10-11 17:20:06 -070028import com.android.internal.R;
29
30import libcore.icu.DateIntervalFormat;
31import libcore.icu.LocaleData;
32import libcore.icu.RelativeDateTimeFormatter;
33
Elliott Hughes6139e642013-07-24 14:46:31 -070034import java.io.IOException;
Neil Fuller7a0837f2019-08-19 15:19:26 +010035import java.time.Instant;
36import java.time.LocalDateTime;
37import java.time.ZoneId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import java.util.Calendar;
39import java.util.Date;
Michael Chanbecfc9d2009-06-29 18:43:44 -070040import java.util.Formatter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import java.util.GregorianCalendar;
Michael Chanbecfc9d2009-06-29 18:43:44 -070042import java.util.Locale;
Tao Bao67bfa0b2015-02-06 15:44:00 -080043import java.util.TimeZone;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044
45/**
46 * This class contains various date-related utilities for creating text for things like
47 * elapsed time and date ranges, strings for days of the week and months, and AM/PM text etc.
48 */
49public class DateUtils
50{
51 private static final Object sLock = new Object();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052 private static Configuration sLastConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053 private static String sElapsedFormatMMSS;
54 private static String sElapsedFormatHMMSS;
Jesse Wilson99a64f42011-11-11 10:56:05 -050055
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056 public static final long SECOND_IN_MILLIS = 1000;
57 public static final long MINUTE_IN_MILLIS = SECOND_IN_MILLIS * 60;
58 public static final long HOUR_IN_MILLIS = MINUTE_IN_MILLIS * 60;
59 public static final long DAY_IN_MILLIS = HOUR_IN_MILLIS * 24;
60 public static final long WEEK_IN_MILLIS = DAY_IN_MILLIS * 7;
Eric Fischer84c863d2009-06-10 12:10:22 -070061 /**
62 * This constant is actually the length of 364 days, not of a year!
63 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064 public static final long YEAR_IN_MILLIS = WEEK_IN_MILLIS * 52;
65
66 // The following FORMAT_* symbols are used for specifying the format of
67 // dates and times in the formatDateRange method.
68 public static final int FORMAT_SHOW_TIME = 0x00001;
69 public static final int FORMAT_SHOW_WEEKDAY = 0x00002;
70 public static final int FORMAT_SHOW_YEAR = 0x00004;
71 public static final int FORMAT_NO_YEAR = 0x00008;
72 public static final int FORMAT_SHOW_DATE = 0x00010;
73 public static final int FORMAT_NO_MONTH_DAY = 0x00020;
Elliott Hughesd3c01012012-08-28 18:57:13 -070074 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075 public static final int FORMAT_12HOUR = 0x00040;
Elliott Hughesd3c01012012-08-28 18:57:13 -070076 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077 public static final int FORMAT_24HOUR = 0x00080;
Elliott Hughesd3c01012012-08-28 18:57:13 -070078 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079 public static final int FORMAT_CAP_AMPM = 0x00100;
80 public static final int FORMAT_NO_NOON = 0x00200;
Elliott Hughesd3c01012012-08-28 18:57:13 -070081 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082 public static final int FORMAT_CAP_NOON = 0x00400;
83 public static final int FORMAT_NO_MIDNIGHT = 0x00800;
Elliott Hughesd3c01012012-08-28 18:57:13 -070084 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085 public static final int FORMAT_CAP_MIDNIGHT = 0x01000;
Erik577ec9e2010-09-01 17:24:53 -070086 /**
87 * @deprecated Use
88 * {@link #formatDateRange(Context, Formatter, long, long, int, String) formatDateRange}
89 * and pass in {@link Time#TIMEZONE_UTC Time.TIMEZONE_UTC} for the timeZone instead.
90 */
91 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092 public static final int FORMAT_UTC = 0x02000;
93 public static final int FORMAT_ABBREV_TIME = 0x04000;
94 public static final int FORMAT_ABBREV_WEEKDAY = 0x08000;
95 public static final int FORMAT_ABBREV_MONTH = 0x10000;
96 public static final int FORMAT_NUMERIC_DATE = 0x20000;
97 public static final int FORMAT_ABBREV_RELATIVE = 0x40000;
98 public static final int FORMAT_ABBREV_ALL = 0x80000;
Elliott Hughesd3c01012012-08-28 18:57:13 -070099 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100 public static final int FORMAT_CAP_NOON_MIDNIGHT = (FORMAT_CAP_NOON | FORMAT_CAP_MIDNIGHT);
Elliott Hughesd3c01012012-08-28 18:57:13 -0700101 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102 public static final int FORMAT_NO_NOON_MIDNIGHT = (FORMAT_NO_NOON | FORMAT_NO_MIDNIGHT);
103
104 // Date and time format strings that are constant and don't need to be
105 // translated.
Eric Fischer84c863d2009-06-10 12:10:22 -0700106 /**
107 * This is not actually the preferred 24-hour date format in all locales.
Elliott Hughesfbf37c72013-03-26 15:11:28 -0700108 * @deprecated Use {@link java.text.SimpleDateFormat} instead.
Eric Fischer84c863d2009-06-10 12:10:22 -0700109 */
Elliott Hughesd3c01012012-08-28 18:57:13 -0700110 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111 public static final String HOUR_MINUTE_24 = "%H:%M";
112 public static final String MONTH_FORMAT = "%B";
Eric Fischer5669ce52009-06-17 18:11:04 -0700113 /**
114 * This is not actually a useful month name in all locales.
Elliott Hughesfbf37c72013-03-26 15:11:28 -0700115 * @deprecated Use {@link java.text.SimpleDateFormat} instead.
Eric Fischer5669ce52009-06-17 18:11:04 -0700116 */
Elliott Hughesd3c01012012-08-28 18:57:13 -0700117 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118 public static final String ABBREV_MONTH_FORMAT = "%b";
119 public static final String NUMERIC_MONTH_FORMAT = "%m";
120 public static final String MONTH_DAY_FORMAT = "%-d";
121 public static final String YEAR_FORMAT = "%Y";
122 public static final String YEAR_FORMAT_TWO_DIGITS = "%g";
123 public static final String WEEKDAY_FORMAT = "%A";
124 public static final String ABBREV_WEEKDAY_FORMAT = "%a";
Jesse Wilson99a64f42011-11-11 10:56:05 -0500125
Elliott Hughesfbf37c72013-03-26 15:11:28 -0700126 /** @deprecated Do not use. */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700127 @Deprecated
Elliott Hughes6139e642013-07-24 14:46:31 -0700128 public static final int[] sameYearTable = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800129
Elliott Hughesfbf37c72013-03-26 15:11:28 -0700130 /** @deprecated Do not use. */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -0700131 @Deprecated
Elliott Hughes6139e642013-07-24 14:46:31 -0700132 public static final int[] sameMonthTable = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800133
134 /**
135 * Request the full spelled-out name. For use with the 'abbrev' parameter of
136 * {@link #getDayOfWeekString} and {@link #getMonthString}.
Jesse Wilson99a64f42011-11-11 10:56:05 -0500137 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138 * @more <p>
139 * e.g. "Sunday" or "January"
Elliott Hughesfbf37c72013-03-26 15:11:28 -0700140 * @deprecated Use {@link java.text.SimpleDateFormat} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141 */
Elliott Hughesd3c01012012-08-28 18:57:13 -0700142 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143 public static final int LENGTH_LONG = 10;
144
145 /**
146 * Request an abbreviated version of the name. For use with the 'abbrev'
147 * parameter of {@link #getDayOfWeekString} and {@link #getMonthString}.
Jesse Wilson99a64f42011-11-11 10:56:05 -0500148 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149 * @more <p>
150 * e.g. "Sun" or "Jan"
Elliott Hughesfbf37c72013-03-26 15:11:28 -0700151 * @deprecated Use {@link java.text.SimpleDateFormat} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800152 */
Elliott Hughesd3c01012012-08-28 18:57:13 -0700153 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154 public static final int LENGTH_MEDIUM = 20;
155
156 /**
157 * Request a shorter abbreviated version of the name.
158 * For use with the 'abbrev' parameter of {@link #getDayOfWeekString} and {@link #getMonthString}.
159 * @more
160 * <p>e.g. "Su" or "Jan"
Eric Fischer5bd644c2009-05-12 16:29:46 -0700161 * <p>In most languages, the results returned for LENGTH_SHORT will be the same as
162 * the results returned for {@link #LENGTH_MEDIUM}.
Elliott Hughesfbf37c72013-03-26 15:11:28 -0700163 * @deprecated Use {@link java.text.SimpleDateFormat} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164 */
Elliott Hughesd3c01012012-08-28 18:57:13 -0700165 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166 public static final int LENGTH_SHORT = 30;
167
168 /**
169 * Request an even shorter abbreviated version of the name.
Eric Fischer5bd644c2009-05-12 16:29:46 -0700170 * Do not use this. Currently this will always return the same result
171 * as {@link #LENGTH_SHORT}.
Elliott Hughesfbf37c72013-03-26 15:11:28 -0700172 * @deprecated Use {@link java.text.SimpleDateFormat} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800173 */
Elliott Hughesd3c01012012-08-28 18:57:13 -0700174 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175 public static final int LENGTH_SHORTER = 40;
176
177 /**
178 * Request an even shorter abbreviated version of the name.
179 * For use with the 'abbrev' parameter of {@link #getDayOfWeekString} and {@link #getMonthString}.
180 * @more
181 * <p>e.g. "S", "T", "T" or "J"
Eric Fischer5bd644c2009-05-12 16:29:46 -0700182 * <p>In some languages, the results returned for LENGTH_SHORTEST will be the same as
183 * the results returned for {@link #LENGTH_SHORT}.
Elliott Hughesfbf37c72013-03-26 15:11:28 -0700184 * @deprecated Use {@link java.text.SimpleDateFormat} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185 */
Elliott Hughesd3c01012012-08-28 18:57:13 -0700186 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187 public static final int LENGTH_SHORTEST = 50;
188
189 /**
190 * Return a string for the day of the week.
191 * @param dayOfWeek One of {@link Calendar#SUNDAY Calendar.SUNDAY},
192 * {@link Calendar#MONDAY Calendar.MONDAY}, etc.
Eric Fischer5bd644c2009-05-12 16:29:46 -0700193 * @param abbrev One of {@link #LENGTH_LONG}, {@link #LENGTH_SHORT},
194 * {@link #LENGTH_MEDIUM}, or {@link #LENGTH_SHORTEST}.
195 * Note that in most languages, {@link #LENGTH_SHORT}
196 * will return the same as {@link #LENGTH_MEDIUM}.
197 * Undefined lengths will return {@link #LENGTH_MEDIUM}
198 * but may return something different in the future.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199 * @throws IndexOutOfBoundsException if the dayOfWeek is out of bounds.
Elliott Hughesfbf37c72013-03-26 15:11:28 -0700200 * @deprecated Use {@link java.text.SimpleDateFormat} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201 */
Elliott Hughesd3c01012012-08-28 18:57:13 -0700202 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203 public static String getDayOfWeekString(int dayOfWeek, int abbrev) {
Elliott Hughes08153ee2012-08-06 15:40:52 -0700204 LocaleData d = LocaleData.get(Locale.getDefault());
205 String[] names;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206 switch (abbrev) {
Elliott Hughes08153ee2012-08-06 15:40:52 -0700207 case LENGTH_LONG: names = d.longWeekdayNames; break;
208 case LENGTH_MEDIUM: names = d.shortWeekdayNames; break;
209 case LENGTH_SHORT: names = d.shortWeekdayNames; break; // TODO
210 case LENGTH_SHORTER: names = d.shortWeekdayNames; break; // TODO
211 case LENGTH_SHORTEST: names = d.tinyWeekdayNames; break;
212 default: names = d.shortWeekdayNames; break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800213 }
Elliott Hughes08153ee2012-08-06 15:40:52 -0700214 return names[dayOfWeek];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800215 }
216
217 /**
218 * Return a localized string for AM or PM.
219 * @param ampm Either {@link Calendar#AM Calendar.AM} or {@link Calendar#PM Calendar.PM}.
220 * @throws IndexOutOfBoundsException if the ampm is out of bounds.
221 * @return Localized version of "AM" or "PM".
Elliott Hughesfbf37c72013-03-26 15:11:28 -0700222 * @deprecated Use {@link java.text.SimpleDateFormat} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223 */
Elliott Hughesd3c01012012-08-28 18:57:13 -0700224 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800225 public static String getAMPMString(int ampm) {
Elliott Hughes4af85342012-07-25 17:30:24 -0700226 return LocaleData.get(Locale.getDefault()).amPm[ampm - Calendar.AM];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227 }
228
229 /**
Eric Fischer5bd644c2009-05-12 16:29:46 -0700230 * Return a localized string for the month of the year.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231 * @param month One of {@link Calendar#JANUARY Calendar.JANUARY},
232 * {@link Calendar#FEBRUARY Calendar.FEBRUARY}, etc.
Eric Fischer5bd644c2009-05-12 16:29:46 -0700233 * @param abbrev One of {@link #LENGTH_LONG}, {@link #LENGTH_MEDIUM},
234 * or {@link #LENGTH_SHORTEST}.
235 * Undefined lengths will return {@link #LENGTH_MEDIUM}
236 * but may return something different in the future.
237 * @return Localized month of the year.
Elliott Hughesfbf37c72013-03-26 15:11:28 -0700238 * @deprecated Use {@link java.text.SimpleDateFormat} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239 */
Elliott Hughesd3c01012012-08-28 18:57:13 -0700240 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241 public static String getMonthString(int month, int abbrev) {
Elliott Hughes08153ee2012-08-06 15:40:52 -0700242 LocaleData d = LocaleData.get(Locale.getDefault());
243 String[] names;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244 switch (abbrev) {
Elliott Hughes08153ee2012-08-06 15:40:52 -0700245 case LENGTH_LONG: names = d.longMonthNames; break;
246 case LENGTH_MEDIUM: names = d.shortMonthNames; break;
247 case LENGTH_SHORT: names = d.shortMonthNames; break;
248 case LENGTH_SHORTER: names = d.shortMonthNames; break;
249 case LENGTH_SHORTEST: names = d.tinyMonthNames; break;
250 default: names = d.shortMonthNames; break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251 }
Elliott Hughes08153ee2012-08-06 15:40:52 -0700252 return names[month];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253 }
254
255 /**
256 * Returns a string describing the elapsed time since startTime.
Tao Bao67bfa0b2015-02-06 15:44:00 -0800257 * <p>
258 * The minimum timespan to report is set to {@link #MINUTE_IN_MILLIS}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800259 * @param startTime some time in the past.
260 * @return a String object containing the elapsed time.
261 * @see #getRelativeTimeSpanString(long, long, long)
262 */
263 public static CharSequence getRelativeTimeSpanString(long startTime) {
264 return getRelativeTimeSpanString(startTime, System.currentTimeMillis(), MINUTE_IN_MILLIS);
265 }
266
267 /**
268 * Returns a string describing 'time' as a time relative to 'now'.
269 * <p>
270 * Time spans in the past are formatted like "42 minutes ago".
Neil Fuller0e1c0e12015-05-28 18:19:02 +0100271 * Time spans in the future are formatted like "In 42 minutes".
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800272 *
273 * @param time the time to describe, in milliseconds
274 * @param now the current time in milliseconds
275 * @param minResolution the minimum timespan to report. For example, a time 3 seconds in the
276 * past will be reported as "0 minutes ago" if this is set to MINUTE_IN_MILLIS. Pass one of
277 * 0, MINUTE_IN_MILLIS, HOUR_IN_MILLIS, DAY_IN_MILLIS, WEEK_IN_MILLIS
278 */
279 public static CharSequence getRelativeTimeSpanString(long time, long now, long minResolution) {
280 int flags = FORMAT_SHOW_DATE | FORMAT_SHOW_YEAR | FORMAT_ABBREV_MONTH;
281 return getRelativeTimeSpanString(time, now, minResolution, flags);
282 }
283
284 /**
285 * Returns a string describing 'time' as a time relative to 'now'.
286 * <p>
287 * Time spans in the past are formatted like "42 minutes ago". Time spans in
Neil Fuller0e1c0e12015-05-28 18:19:02 +0100288 * the future are formatted like "In 42 minutes".
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800289 * <p>
290 * Can use {@link #FORMAT_ABBREV_RELATIVE} flag to use abbreviated relative
291 * times, like "42 mins ago".
Jesse Wilson99a64f42011-11-11 10:56:05 -0500292 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800293 * @param time the time to describe, in milliseconds
294 * @param now the current time in milliseconds
295 * @param minResolution the minimum timespan to report. For example, a time
296 * 3 seconds in the past will be reported as "0 minutes ago" if
297 * this is set to MINUTE_IN_MILLIS. Pass one of 0,
298 * MINUTE_IN_MILLIS, HOUR_IN_MILLIS, DAY_IN_MILLIS,
299 * WEEK_IN_MILLIS
300 * @param flags a bit mask of formatting options, such as
301 * {@link #FORMAT_NUMERIC_DATE} or
302 * {@link #FORMAT_ABBREV_RELATIVE}
303 */
304 public static CharSequence getRelativeTimeSpanString(long time, long now, long minResolution,
305 int flags) {
Tao Bao67bfa0b2015-02-06 15:44:00 -0800306 return RelativeDateTimeFormatter.getRelativeTimeSpanString(Locale.getDefault(),
307 TimeZone.getDefault(), time, now, minResolution, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800308 }
Jesse Wilson99a64f42011-11-11 10:56:05 -0500309
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800310 /**
311 * Return string describing the elapsed time since startTime formatted like
312 * "[relative time/date], [time]".
313 * <p>
314 * Example output strings for the US date format.
315 * <ul>
Tao Bao67bfa0b2015-02-06 15:44:00 -0800316 * <li>3 min. ago, 10:15 AM</li>
317 * <li>Yesterday, 12:20 PM</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800318 * <li>Dec 12, 4:12 AM</li>
319 * <li>11/14/2007, 8:20 AM</li>
320 * </ul>
Jesse Wilson99a64f42011-11-11 10:56:05 -0500321 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800322 * @param time some time in the past.
323 * @param minResolution the minimum elapsed time (in milliseconds) to report
324 * when showing relative times. For example, a time 3 seconds in
325 * the past will be reported as "0 minutes ago" if this is set to
326 * {@link #MINUTE_IN_MILLIS}.
327 * @param transitionResolution the elapsed time (in milliseconds) at which
328 * to stop reporting relative measurements. Elapsed times greater
329 * than this resolution will default to normal date formatting.
Tao Bao67bfa0b2015-02-06 15:44:00 -0800330 * For example, will transition from "7 days ago" to "Dec 12"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800331 * when using {@link #WEEK_IN_MILLIS}.
332 */
333 public static CharSequence getRelativeDateTimeString(Context c, long time, long minResolution,
334 long transitionResolution, int flags) {
Tao Bao67bfa0b2015-02-06 15:44:00 -0800335 // Same reason as in formatDateRange() to explicitly indicate 12- or 24-hour format.
336 if ((flags & (FORMAT_SHOW_TIME | FORMAT_12HOUR | FORMAT_24HOUR)) == FORMAT_SHOW_TIME) {
337 flags |= DateFormat.is24HourFormat(c) ? FORMAT_24HOUR : FORMAT_12HOUR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800338 }
339
Tao Bao67bfa0b2015-02-06 15:44:00 -0800340 return RelativeDateTimeFormatter.getRelativeDateTimeString(Locale.getDefault(),
341 TimeZone.getDefault(), time, System.currentTimeMillis(), minResolution,
342 transitionResolution, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800343 }
344
345 private static void initFormatStrings() {
346 synchronized (sLock) {
Jozef BABJAK25d8b052011-02-22 09:17:51 +0100347 initFormatStringsLocked();
348 }
349 }
350
351 private static void initFormatStringsLocked() {
352 Resources r = Resources.getSystem();
353 Configuration cfg = r.getConfiguration();
354 if (sLastConfig == null || !sLastConfig.equals(cfg)) {
355 sLastConfig = cfg;
Jozef BABJAK25d8b052011-02-22 09:17:51 +0100356 sElapsedFormatMMSS = r.getString(com.android.internal.R.string.elapsed_time_short_format_mm_ss);
357 sElapsedFormatHMMSS = r.getString(com.android.internal.R.string.elapsed_time_short_format_h_mm_ss);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800358 }
359 }
360
361 /**
Roozbeh Pournaderc6bffbf2016-12-13 13:58:56 -0800362 * Returns the given duration in a human-friendly format. For example,
363 * "4 minutes" or "1 second". Returns only the largest meaningful unit of time,
Jeff Sharkey53f6e8a2012-11-13 16:23:59 -0800364 * from seconds up to hours.
365 *
366 * @hide
367 */
Mathew Inwoodefeab842018-08-14 15:21:30 +0100368 @UnsupportedAppUsage
Jeff Sharkey53f6e8a2012-11-13 16:23:59 -0800369 public static CharSequence formatDuration(long millis) {
Roozbeh Pournaderc6bffbf2016-12-13 13:58:56 -0800370 return formatDuration(millis, LENGTH_LONG);
371 }
372
373 /**
374 * Returns the given duration in a human-friendly format. For example,
375 * "4 minutes" or "1 second". Returns only the largest meaningful unit of time,
376 * from seconds up to hours.
377 * <p>
378 * You can use abbrev to specify a preference for abbreviations (but note that some
379 * locales may not have abbreviations). Use LENGTH_LONG for the full spelling (e.g. "2 hours"),
380 * LENGTH_SHORT for the abbreviated spelling if available (e.g. "2 hr"), and LENGTH_SHORTEST for
381 * the briefest form available (e.g. "2h").
382 * @hide
383 */
Mathew Inwoodefeab842018-08-14 15:21:30 +0100384 @UnsupportedAppUsage
Roozbeh Pournaderc6bffbf2016-12-13 13:58:56 -0800385 public static CharSequence formatDuration(long millis, int abbrev) {
386 final FormatWidth width;
387 switch (abbrev) {
388 case LENGTH_LONG:
389 width = FormatWidth.WIDE;
390 break;
391 case LENGTH_SHORT:
392 case LENGTH_SHORTER:
393 case LENGTH_MEDIUM:
394 width = FormatWidth.SHORT;
395 break;
396 case LENGTH_SHORTEST:
397 width = FormatWidth.NARROW;
398 break;
399 default:
400 width = FormatWidth.WIDE;
401 }
402 final MeasureFormat formatter = MeasureFormat.getInstance(Locale.getDefault(), width);
Jeff Sharkey53f6e8a2012-11-13 16:23:59 -0800403 if (millis >= HOUR_IN_MILLIS) {
404 final int hours = (int) ((millis + 1800000) / HOUR_IN_MILLIS);
Roozbeh Pournaderc6bffbf2016-12-13 13:58:56 -0800405 return formatter.format(new Measure(hours, MeasureUnit.HOUR));
Jeff Sharkey53f6e8a2012-11-13 16:23:59 -0800406 } else if (millis >= MINUTE_IN_MILLIS) {
407 final int minutes = (int) ((millis + 30000) / MINUTE_IN_MILLIS);
Roozbeh Pournaderc6bffbf2016-12-13 13:58:56 -0800408 return formatter.format(new Measure(minutes, MeasureUnit.MINUTE));
Jeff Sharkey53f6e8a2012-11-13 16:23:59 -0800409 } else {
410 final int seconds = (int) ((millis + 500) / SECOND_IN_MILLIS);
Roozbeh Pournaderc6bffbf2016-12-13 13:58:56 -0800411 return formatter.format(new Measure(seconds, MeasureUnit.SECOND));
Jeff Sharkey53f6e8a2012-11-13 16:23:59 -0800412 }
413 }
414
415 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800416 * Formats an elapsed time in the form "MM:SS" or "H:MM:SS"
417 * for display on the call-in-progress screen.
418 * @param elapsedSeconds the elapsed time in seconds.
419 */
420 public static String formatElapsedTime(long elapsedSeconds) {
421 return formatElapsedTime(null, elapsedSeconds);
422 }
Jesse Wilson99a64f42011-11-11 10:56:05 -0500423
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800424 /**
Elliott Hughes2eda1842012-12-14 14:29:47 -0800425 * Formats an elapsed time in a format like "MM:SS" or "H:MM:SS" (using a form
426 * suited to the current locale), similar to that used on the call-in-progress
427 * screen.
Jesse Wilson99a64f42011-11-11 10:56:05 -0500428 *
Elliott Hughes2eda1842012-12-14 14:29:47 -0800429 * @param recycle {@link StringBuilder} to recycle, or null to use a temporary one.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800430 * @param elapsedSeconds the elapsed time in seconds.
431 */
432 public static String formatElapsedTime(StringBuilder recycle, long elapsedSeconds) {
Elliott Hughes2eda1842012-12-14 14:29:47 -0800433 // Break the elapsed seconds into hours, minutes, and seconds.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800434 long hours = 0;
435 long minutes = 0;
436 long seconds = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800437 if (elapsedSeconds >= 3600) {
438 hours = elapsedSeconds / 3600;
439 elapsedSeconds -= hours * 3600;
440 }
441 if (elapsedSeconds >= 60) {
442 minutes = elapsedSeconds / 60;
443 elapsedSeconds -= minutes * 60;
444 }
445 seconds = elapsedSeconds;
446
Elliott Hughes2eda1842012-12-14 14:29:47 -0800447 // Create a StringBuilder if we weren't given one to recycle.
448 // TODO: if we cared, we could have a thread-local temporary StringBuilder.
449 StringBuilder sb = recycle;
450 if (sb == null) {
451 sb = new StringBuilder(8);
452 } else {
453 sb.setLength(0);
454 }
455
456 // Format the broken-down time in a locale-appropriate way.
457 // TODO: use icu4c when http://unicode.org/cldr/trac/ticket/3407 is fixed.
458 Formatter f = new Formatter(sb, Locale.getDefault());
459 initFormatStrings();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800460 if (hours > 0) {
Elliott Hughes2eda1842012-12-14 14:29:47 -0800461 return f.format(sElapsedFormatHMMSS, hours, minutes, seconds).toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800462 } else {
Elliott Hughes2eda1842012-12-14 14:29:47 -0800463 return f.format(sElapsedFormatMMSS, minutes, seconds).toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800464 }
465 }
466
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800467 /**
468 * Format a date / time such that if the then is on the same day as now, it shows
469 * just the time and if it's a different day, it shows just the date.
Jesse Wilson99a64f42011-11-11 10:56:05 -0500470 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800471 * <p>The parameters dateFormat and timeFormat should each be one of
472 * {@link java.text.DateFormat#DEFAULT},
473 * {@link java.text.DateFormat#FULL},
474 * {@link java.text.DateFormat#LONG},
475 * {@link java.text.DateFormat#MEDIUM}
476 * or
477 * {@link java.text.DateFormat#SHORT}
478 *
479 * @param then the date to format
480 * @param now the base time
481 * @param dateStyle how to format the date portion.
482 * @param timeStyle how to format the time portion.
483 */
484 public static final CharSequence formatSameDayTime(long then, long now,
485 int dateStyle, int timeStyle) {
486 Calendar thenCal = new GregorianCalendar();
487 thenCal.setTimeInMillis(then);
488 Date thenDate = thenCal.getTime();
489 Calendar nowCal = new GregorianCalendar();
490 nowCal.setTimeInMillis(now);
491
492 java.text.DateFormat f;
493
494 if (thenCal.get(Calendar.YEAR) == nowCal.get(Calendar.YEAR)
495 && thenCal.get(Calendar.MONTH) == nowCal.get(Calendar.MONTH)
496 && thenCal.get(Calendar.DAY_OF_MONTH) == nowCal.get(Calendar.DAY_OF_MONTH)) {
497 f = java.text.DateFormat.getTimeInstance(timeStyle);
498 } else {
499 f = java.text.DateFormat.getDateInstance(dateStyle);
500 }
501 return f.format(thenDate);
502 }
503
504 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800505 * @return true if the supplied when is today else false
506 */
507 public static boolean isToday(long when) {
Neil Fuller7a0837f2019-08-19 15:19:26 +0100508 return isSameDate(when, System.currentTimeMillis());
509 }
Jesse Wilson99a64f42011-11-11 10:56:05 -0500510
Neil Fuller7a0837f2019-08-19 15:19:26 +0100511 private static boolean isSameDate(long oneMillis, long twoMillis) {
512 ZoneId zoneId = ZoneId.systemDefault();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800513
Neil Fuller7a0837f2019-08-19 15:19:26 +0100514 Instant oneInstant = Instant.ofEpochMilli(oneMillis);
515 LocalDateTime oneLocalDateTime = LocalDateTime.ofInstant(oneInstant, zoneId);
516
517 Instant twoInstant = Instant.ofEpochMilli(twoMillis);
518 LocalDateTime twoLocalDateTime = LocalDateTime.ofInstant(twoInstant, zoneId);
519
520 return (oneLocalDateTime.getYear() == twoLocalDateTime.getYear())
521 && (oneLocalDateTime.getMonthValue() == twoLocalDateTime.getMonthValue())
522 && (oneLocalDateTime.getDayOfMonth() == twoLocalDateTime.getDayOfMonth());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800523 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800524
525 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800526 * Formats a date or a time range according to the local conventions.
Michael Chanbecfc9d2009-06-29 18:43:44 -0700527 * <p>
528 * Note that this is a convenience method. Using it involves creating an
529 * internal {@link java.util.Formatter} instance on-the-fly, which is
530 * somewhat costly in terms of memory and time. This is probably acceptable
531 * if you use the method only rarely, but if you rely on it for formatting a
532 * large number of dates, consider creating and reusing your own
533 * {@link java.util.Formatter} instance and use the version of
534 * {@link #formatDateRange(Context, long, long, int) formatDateRange}
535 * that takes a {@link java.util.Formatter}.
Erik577ec9e2010-09-01 17:24:53 -0700536 *
Michael Chanbecfc9d2009-06-29 18:43:44 -0700537 * @param context the context is required only if the time is shown
538 * @param startMillis the start time in UTC milliseconds
539 * @param endMillis the end time in UTC milliseconds
540 * @param flags a bit mask of options See
Erik577ec9e2010-09-01 17:24:53 -0700541 * {@link #formatDateRange(Context, Formatter, long, long, int, String) formatDateRange}
Michael Chanbecfc9d2009-06-29 18:43:44 -0700542 * @return a string containing the formatted date/time range.
543 */
544 public static String formatDateRange(Context context, long startMillis,
545 long endMillis, int flags) {
546 Formatter f = new Formatter(new StringBuilder(50), Locale.getDefault());
547 return formatDateRange(context, f, startMillis, endMillis, flags).toString();
548 }
549
550 /**
551 * Formats a date or a time range according to the local conventions.
Erik577ec9e2010-09-01 17:24:53 -0700552 * <p>
553 * Note that this is a convenience method for formatting the date or
554 * time range in the local time zone. If you want to specify the time
555 * zone please use
556 * {@link #formatDateRange(Context, Formatter, long, long, int, String) formatDateRange}.
557 *
558 * @param context the context is required only if the time is shown
559 * @param formatter the Formatter used for formatting the date range.
560 * Note: be sure to call setLength(0) on StringBuilder passed to
561 * the Formatter constructor unless you want the results to accumulate.
562 * @param startMillis the start time in UTC milliseconds
563 * @param endMillis the end time in UTC milliseconds
564 * @param flags a bit mask of options See
565 * {@link #formatDateRange(Context, Formatter, long, long, int, String) formatDateRange}
566 * @return a string containing the formatted date/time range.
567 */
568 public static Formatter formatDateRange(Context context, Formatter formatter, long startMillis,
569 long endMillis, int flags) {
570 return formatDateRange(context, formatter, startMillis, endMillis, flags, null);
571 }
572
573 /**
574 * Formats a date or a time range according to the local conventions.
Jesse Wilson99a64f42011-11-11 10:56:05 -0500575 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800576 * <p>
577 * Example output strings (date formats in these examples are shown using
578 * the US date format convention but that may change depending on the
579 * local settings):
580 * <ul>
581 * <li>10:15am</li>
582 * <li>3:00pm - 4:00pm</li>
583 * <li>3pm - 4pm</li>
584 * <li>3PM - 4PM</li>
585 * <li>08:00 - 17:00</li>
586 * <li>Oct 9</li>
587 * <li>Tue, Oct 9</li>
588 * <li>October 9, 2007</li>
589 * <li>Oct 9 - 10</li>
590 * <li>Oct 9 - 10, 2007</li>
591 * <li>Oct 28 - Nov 3, 2007</li>
592 * <li>Dec 31, 2007 - Jan 1, 2008</li>
593 * <li>Oct 9, 8:00am - Oct 10, 5:00pm</li>
594 * <li>12/31/2007 - 01/01/2008</li>
595 * </ul>
Jesse Wilson99a64f42011-11-11 10:56:05 -0500596 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800597 * <p>
598 * The flags argument is a bitmask of options from the following list:
Jesse Wilson99a64f42011-11-11 10:56:05 -0500599 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800600 * <ul>
601 * <li>FORMAT_SHOW_TIME</li>
602 * <li>FORMAT_SHOW_WEEKDAY</li>
603 * <li>FORMAT_SHOW_YEAR</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800604 * <li>FORMAT_SHOW_DATE</li>
605 * <li>FORMAT_NO_MONTH_DAY</li>
606 * <li>FORMAT_12HOUR</li>
607 * <li>FORMAT_24HOUR</li>
608 * <li>FORMAT_CAP_AMPM</li>
609 * <li>FORMAT_NO_NOON</li>
610 * <li>FORMAT_CAP_NOON</li>
611 * <li>FORMAT_NO_MIDNIGHT</li>
612 * <li>FORMAT_CAP_MIDNIGHT</li>
613 * <li>FORMAT_UTC</li>
614 * <li>FORMAT_ABBREV_TIME</li>
615 * <li>FORMAT_ABBREV_WEEKDAY</li>
616 * <li>FORMAT_ABBREV_MONTH</li>
617 * <li>FORMAT_ABBREV_ALL</li>
618 * <li>FORMAT_NUMERIC_DATE</li>
619 * </ul>
Jesse Wilson99a64f42011-11-11 10:56:05 -0500620 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800621 * <p>
622 * If FORMAT_SHOW_TIME is set, the time is shown as part of the date range.
623 * If the start and end time are the same, then just the start time is
624 * shown.
Jesse Wilson99a64f42011-11-11 10:56:05 -0500625 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800626 * <p>
627 * If FORMAT_SHOW_WEEKDAY is set, then the weekday is shown.
Jesse Wilson99a64f42011-11-11 10:56:05 -0500628 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800629 * <p>
630 * If FORMAT_SHOW_YEAR is set, then the year is always shown.
Elliott Hughes6139e642013-07-24 14:46:31 -0700631 * If FORMAT_SHOW_YEAR is not set, then the year
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800632 * is shown only if it is different from the current year, or if the start
Elliott Hughes6139e642013-07-24 14:46:31 -0700633 * and end dates fall on different years.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800634 *
635 * <p>
636 * Normally the date is shown unless the start and end day are the same.
637 * If FORMAT_SHOW_DATE is set, then the date is always shown, even for
638 * same day ranges.
Jesse Wilson99a64f42011-11-11 10:56:05 -0500639 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800640 * <p>
641 * If FORMAT_NO_MONTH_DAY is set, then if the date is shown, just the
642 * month name will be shown, not the day of the month. For example,
643 * "January, 2008" instead of "January 6 - 12, 2008".
Jesse Wilson99a64f42011-11-11 10:56:05 -0500644 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800645 * <p>
646 * If FORMAT_CAP_AMPM is set and 12-hour time is used, then the "AM"
Eric Fischer84c863d2009-06-10 12:10:22 -0700647 * and "PM" are capitalized. You should not use this flag
648 * because in some locales these terms cannot be capitalized, and in
649 * many others it doesn't make sense to do so even though it is possible.
Jesse Wilson99a64f42011-11-11 10:56:05 -0500650 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800651 * <p>
652 * If FORMAT_NO_NOON is set and 12-hour time is used, then "12pm" is
653 * shown instead of "noon".
Jesse Wilson99a64f42011-11-11 10:56:05 -0500654 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800655 * <p>
656 * If FORMAT_CAP_NOON is set and 12-hour time is used, then "Noon" is
Eric Fischer84c863d2009-06-10 12:10:22 -0700657 * shown instead of "noon". You should probably not use this flag
658 * because in many locales it will not make sense to capitalize
659 * the term.
Jesse Wilson99a64f42011-11-11 10:56:05 -0500660 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800661 * <p>
662 * If FORMAT_NO_MIDNIGHT is set and 12-hour time is used, then "12am" is
663 * shown instead of "midnight".
Jesse Wilson99a64f42011-11-11 10:56:05 -0500664 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800665 * <p>
Eric Fischer84c863d2009-06-10 12:10:22 -0700666 * If FORMAT_CAP_MIDNIGHT is set and 12-hour time is used, then "Midnight"
667 * is shown instead of "midnight". You should probably not use this
668 * flag because in many locales it will not make sense to capitalize
669 * the term.
Jesse Wilson99a64f42011-11-11 10:56:05 -0500670 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800671 * <p>
672 * If FORMAT_12HOUR is set and the time is shown, then the time is
673 * shown in the 12-hour time format. You should not normally set this.
674 * Instead, let the time format be chosen automatically according to the
675 * system settings. If both FORMAT_12HOUR and FORMAT_24HOUR are set, then
676 * FORMAT_24HOUR takes precedence.
Jesse Wilson99a64f42011-11-11 10:56:05 -0500677 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800678 * <p>
679 * If FORMAT_24HOUR is set and the time is shown, then the time is
680 * shown in the 24-hour time format. You should not normally set this.
681 * Instead, let the time format be chosen automatically according to the
682 * system settings. If both FORMAT_12HOUR and FORMAT_24HOUR are set, then
683 * FORMAT_24HOUR takes precedence.
Jesse Wilson99a64f42011-11-11 10:56:05 -0500684 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685 * <p>
Erik577ec9e2010-09-01 17:24:53 -0700686 * If FORMAT_UTC is set, then the UTC time zone is used for the start
687 * and end milliseconds unless a time zone is specified. If a time zone
688 * is specified it will be used regardless of the FORMAT_UTC flag.
Jesse Wilson99a64f42011-11-11 10:56:05 -0500689 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690 * <p>
691 * If FORMAT_ABBREV_TIME is set and 12-hour time format is used, then the
692 * start and end times (if shown) are abbreviated by not showing the minutes
693 * if they are zero. For example, instead of "3:00pm" the time would be
694 * abbreviated to "3pm".
Jesse Wilson99a64f42011-11-11 10:56:05 -0500695 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696 * <p>
697 * If FORMAT_ABBREV_WEEKDAY is set, then the weekday (if shown) is
698 * abbreviated to a 3-letter string.
Jesse Wilson99a64f42011-11-11 10:56:05 -0500699 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800700 * <p>
701 * If FORMAT_ABBREV_MONTH is set, then the month (if shown) is abbreviated
702 * to a 3-letter string.
Jesse Wilson99a64f42011-11-11 10:56:05 -0500703 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800704 * <p>
705 * If FORMAT_ABBREV_ALL is set, then the weekday and the month (if shown)
706 * are abbreviated to 3-letter strings.
Jesse Wilson99a64f42011-11-11 10:56:05 -0500707 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800708 * <p>
709 * If FORMAT_NUMERIC_DATE is set, then the date is shown in numeric format
710 * instead of using the name of the month. For example, "12/31/2008"
711 * instead of "December 31, 2008".
Jesse Wilson99a64f42011-11-11 10:56:05 -0500712 *
713 * <p>
714 * If the end date ends at 12:00am at the beginning of a day, it is
715 * formatted as the end of the previous day in two scenarios:
716 * <ul>
717 * <li>For single day events. This results in "8pm - midnight" instead of
718 * "Nov 10, 8pm - Nov 11, 12am".</li>
719 * <li>When the time is not displayed. This results in "Nov 10 - 11" for
720 * an event with a start date of Nov 10 and an end date of Nov 12 at
721 * 00:00.</li>
722 * </ul>
723 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 * @param context the context is required only if the time is shown
Michael Chanbecfc9d2009-06-29 18:43:44 -0700725 * @param formatter the Formatter used for formatting the date range.
726 * Note: be sure to call setLength(0) on StringBuilder passed to
727 * the Formatter constructor unless you want the results to accumulate.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800728 * @param startMillis the start time in UTC milliseconds
729 * @param endMillis the end time in UTC milliseconds
730 * @param flags a bit mask of options
Erik577ec9e2010-09-01 17:24:53 -0700731 * @param timeZone the time zone to compute the string in. Use null for local
732 * or if the FORMAT_UTC flag is being used.
Jesse Wilson99a64f42011-11-11 10:56:05 -0500733 *
Michael Chanbecfc9d2009-06-29 18:43:44 -0700734 * @return the formatter with the formatted date/time range appended to the string buffer.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800735 */
Michael Chanbecfc9d2009-06-29 18:43:44 -0700736 public static Formatter formatDateRange(Context context, Formatter formatter, long startMillis,
Elliott Hughesf0b79ae2013-08-14 15:12:43 -0700737 long endMillis, int flags, String timeZone) {
Elliott Hughes8d8ef002013-08-16 11:56:35 -0700738 // If we're being asked to format a time without being explicitly told whether to use
739 // the 12- or 24-hour clock, icu4c will fall back to the locale's preferred 12/24 format,
Elliott Hughesf0b79ae2013-08-14 15:12:43 -0700740 // but we want to fall back to the user's preference.
Elliott Hughes8d8ef002013-08-16 11:56:35 -0700741 if ((flags & (FORMAT_SHOW_TIME | FORMAT_12HOUR | FORMAT_24HOUR)) == FORMAT_SHOW_TIME) {
Elliott Hughesf0b79ae2013-08-14 15:12:43 -0700742 flags |= DateFormat.is24HourFormat(context) ? FORMAT_24HOUR : FORMAT_12HOUR;
743 }
744
Elliott Hughes6139e642013-07-24 14:46:31 -0700745 String range = DateIntervalFormat.formatDateRange(startMillis, endMillis, flags, timeZone);
746 try {
747 formatter.out().append(range);
748 } catch (IOException impossible) {
749 throw new AssertionError(impossible);
Erik577ec9e2010-09-01 17:24:53 -0700750 }
Elliott Hughes6139e642013-07-24 14:46:31 -0700751 return formatter;
Sungmin Choi9a2ada42013-02-28 20:17:15 +0900752 }
753
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800754 /**
755 * Formats a date or a time according to the local conventions. There are
756 * lots of options that allow the caller to control, for example, if the
757 * time is shown, if the day of the week is shown, if the month name is
758 * abbreviated, if noon is shown instead of 12pm, and so on. For the
759 * complete list of options, see the documentation for
760 * {@link #formatDateRange}.
761 * <p>
762 * Example output strings (date formats in these examples are shown using
763 * the US date format convention but that may change depending on the
764 * local settings):
765 * <ul>
766 * <li>10:15am</li>
767 * <li>3:00pm</li>
768 * <li>3pm</li>
769 * <li>3PM</li>
770 * <li>08:00</li>
771 * <li>17:00</li>
772 * <li>noon</li>
773 * <li>Noon</li>
774 * <li>midnight</li>
775 * <li>Midnight</li>
776 * <li>Oct 31</li>
777 * <li>Oct 31, 2007</li>
778 * <li>October 31, 2007</li>
779 * <li>10am, Oct 31</li>
780 * <li>17:00, Oct 31</li>
781 * <li>Wed</li>
782 * <li>Wednesday</li>
783 * <li>10am, Wed, Oct 31</li>
784 * <li>Wed, Oct 31</li>
785 * <li>Wednesday, Oct 31</li>
786 * <li>Wed, Oct 31, 2007</li>
787 * <li>Wed, October 31</li>
788 * <li>10/31/2007</li>
789 * </ul>
Jesse Wilson99a64f42011-11-11 10:56:05 -0500790 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800791 * @param context the context is required only if the time is shown
792 * @param millis a point in time in UTC milliseconds
793 * @param flags a bit mask of formatting options
794 * @return a string containing the formatted date/time.
795 */
796 public static String formatDateTime(Context context, long millis, int flags) {
797 return formatDateRange(context, millis, millis, flags);
798 }
799
800 /**
801 * @return a relative time string to display the time expressed by millis. Times
802 * are counted starting at midnight, which means that assuming that the current
803 * time is March 31st, 0:30:
804 * <ul>
Jesse Wilson99a64f42011-11-11 10:56:05 -0500805 * <li>"millis=0:10 today" will be displayed as "0:10"</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800806 * <li>"millis=11:30pm the day before" will be displayed as "Mar 30"</li>
807 * </ul>
808 * If the given millis is in a different year, then the full date is
809 * returned in numeric format (e.g., "10/12/2008").
Jesse Wilson99a64f42011-11-11 10:56:05 -0500810 *
811 * @param withPreposition If true, the string returned will include the correct
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800812 * preposition ("at 9:20am", "on 10/12/2008" or "on May 29").
813 */
814 public static CharSequence getRelativeTimeSpanString(Context c, long millis,
815 boolean withPreposition) {
816
David Sobreira Marques6a84af02010-03-28 19:39:17 -0300817 String result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800818 long now = System.currentTimeMillis();
Steve Pomeroyca336372012-08-27 02:20:13 -0400819 long span = Math.abs(now - millis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800820
David Sobreira Marques6a84af02010-03-28 19:39:17 -0300821 synchronized (DateUtils.class) {
822 if (sNowTime == null) {
823 sNowTime = new Time();
824 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800825
David Sobreira Marques6a84af02010-03-28 19:39:17 -0300826 if (sThenTime == null) {
827 sThenTime = new Time();
828 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800829
David Sobreira Marques6a84af02010-03-28 19:39:17 -0300830 sNowTime.set(now);
831 sThenTime.set(millis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832
David Sobreira Marques6a84af02010-03-28 19:39:17 -0300833 int prepositionId;
834 if (span < DAY_IN_MILLIS && sNowTime.weekDay == sThenTime.weekDay) {
835 // Same day
836 int flags = FORMAT_SHOW_TIME;
837 result = formatDateRange(c, millis, millis, flags);
838 prepositionId = R.string.preposition_for_time;
839 } else if (sNowTime.year != sThenTime.year) {
840 // Different years
841 int flags = FORMAT_SHOW_DATE | FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE;
842 result = formatDateRange(c, millis, millis, flags);
843
844 // This is a date (like "10/31/2008" so use the date preposition)
845 prepositionId = R.string.preposition_for_date;
846 } else {
847 // Default
848 int flags = FORMAT_SHOW_DATE | FORMAT_ABBREV_MONTH;
849 result = formatDateRange(c, millis, millis, flags);
850 prepositionId = R.string.preposition_for_date;
851 }
852 if (withPreposition) {
853 Resources res = c.getResources();
854 result = res.getString(prepositionId, result);
855 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856 }
857 return result;
858 }
Jesse Wilson99a64f42011-11-11 10:56:05 -0500859
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 /**
Jesse Wilson99a64f42011-11-11 10:56:05 -0500861 * Convenience function to return relative time string without preposition.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800862 * @param c context for resources
863 * @param millis time in milliseconds
864 * @return {@link CharSequence} containing relative time.
865 * @see #getRelativeTimeSpanString(Context, long, boolean)
866 */
867 public static CharSequence getRelativeTimeSpanString(Context c, long millis) {
868 return getRelativeTimeSpanString(c, millis, false /* no preposition */);
869 }
Jesse Wilson99a64f42011-11-11 10:56:05 -0500870
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800871 private static Time sNowTime;
872 private static Time sThenTime;
873}