blob: d0ed8715828c9bc11d244f6dc2e8b488f067e3e0 [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
19import com.android.internal.R;
20
21import android.content.Context;
22import android.content.res.Configuration;
23import android.content.res.Resources;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024
Elliott Hughes6139e642013-07-24 14:46:31 -070025import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026import java.util.Calendar;
27import java.util.Date;
Michael Chanbecfc9d2009-06-29 18:43:44 -070028import java.util.Formatter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import java.util.GregorianCalendar;
Michael Chanbecfc9d2009-06-29 18:43:44 -070030import java.util.Locale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031
Elliott Hughes6139e642013-07-24 14:46:31 -070032import libcore.icu.DateIntervalFormat;
Elliott Hughes4af85342012-07-25 17:30:24 -070033import libcore.icu.LocaleData;
34
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035/**
36 * This class contains various date-related utilities for creating text for things like
37 * elapsed time and date ranges, strings for days of the week and months, and AM/PM text etc.
38 */
39public class DateUtils
40{
41 private static final Object sLock = new Object();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042 private static Configuration sLastConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043 private static String sElapsedFormatMMSS;
44 private static String sElapsedFormatHMMSS;
Jesse Wilson99a64f42011-11-11 10:56:05 -050045
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046 public static final long SECOND_IN_MILLIS = 1000;
47 public static final long MINUTE_IN_MILLIS = SECOND_IN_MILLIS * 60;
48 public static final long HOUR_IN_MILLIS = MINUTE_IN_MILLIS * 60;
49 public static final long DAY_IN_MILLIS = HOUR_IN_MILLIS * 24;
50 public static final long WEEK_IN_MILLIS = DAY_IN_MILLIS * 7;
Eric Fischer84c863d2009-06-10 12:10:22 -070051 /**
52 * This constant is actually the length of 364 days, not of a year!
53 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054 public static final long YEAR_IN_MILLIS = WEEK_IN_MILLIS * 52;
55
56 // The following FORMAT_* symbols are used for specifying the format of
57 // dates and times in the formatDateRange method.
58 public static final int FORMAT_SHOW_TIME = 0x00001;
59 public static final int FORMAT_SHOW_WEEKDAY = 0x00002;
60 public static final int FORMAT_SHOW_YEAR = 0x00004;
61 public static final int FORMAT_NO_YEAR = 0x00008;
62 public static final int FORMAT_SHOW_DATE = 0x00010;
63 public static final int FORMAT_NO_MONTH_DAY = 0x00020;
Elliott Hughesd3c01012012-08-28 18:57:13 -070064 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065 public static final int FORMAT_12HOUR = 0x00040;
Elliott Hughesd3c01012012-08-28 18:57:13 -070066 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067 public static final int FORMAT_24HOUR = 0x00080;
Elliott Hughesd3c01012012-08-28 18:57:13 -070068 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069 public static final int FORMAT_CAP_AMPM = 0x00100;
70 public static final int FORMAT_NO_NOON = 0x00200;
Elliott Hughesd3c01012012-08-28 18:57:13 -070071 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072 public static final int FORMAT_CAP_NOON = 0x00400;
73 public static final int FORMAT_NO_MIDNIGHT = 0x00800;
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_CAP_MIDNIGHT = 0x01000;
Erik577ec9e2010-09-01 17:24:53 -070076 /**
77 * @deprecated Use
78 * {@link #formatDateRange(Context, Formatter, long, long, int, String) formatDateRange}
79 * and pass in {@link Time#TIMEZONE_UTC Time.TIMEZONE_UTC} for the timeZone instead.
80 */
81 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082 public static final int FORMAT_UTC = 0x02000;
83 public static final int FORMAT_ABBREV_TIME = 0x04000;
84 public static final int FORMAT_ABBREV_WEEKDAY = 0x08000;
85 public static final int FORMAT_ABBREV_MONTH = 0x10000;
86 public static final int FORMAT_NUMERIC_DATE = 0x20000;
87 public static final int FORMAT_ABBREV_RELATIVE = 0x40000;
88 public static final int FORMAT_ABBREV_ALL = 0x80000;
Elliott Hughesd3c01012012-08-28 18:57:13 -070089 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090 public static final int FORMAT_CAP_NOON_MIDNIGHT = (FORMAT_CAP_NOON | FORMAT_CAP_MIDNIGHT);
Elliott Hughesd3c01012012-08-28 18:57:13 -070091 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092 public static final int FORMAT_NO_NOON_MIDNIGHT = (FORMAT_NO_NOON | FORMAT_NO_MIDNIGHT);
93
94 // Date and time format strings that are constant and don't need to be
95 // translated.
Eric Fischer84c863d2009-06-10 12:10:22 -070096 /**
97 * This is not actually the preferred 24-hour date format in all locales.
Elliott Hughesfbf37c72013-03-26 15:11:28 -070098 * @deprecated Use {@link java.text.SimpleDateFormat} instead.
Eric Fischer84c863d2009-06-10 12:10:22 -070099 */
Elliott Hughesd3c01012012-08-28 18:57:13 -0700100 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101 public static final String HOUR_MINUTE_24 = "%H:%M";
102 public static final String MONTH_FORMAT = "%B";
Eric Fischer5669ce52009-06-17 18:11:04 -0700103 /**
104 * This is not actually a useful month name in all locales.
Elliott Hughesfbf37c72013-03-26 15:11:28 -0700105 * @deprecated Use {@link java.text.SimpleDateFormat} instead.
Eric Fischer5669ce52009-06-17 18:11:04 -0700106 */
Elliott Hughesd3c01012012-08-28 18:57:13 -0700107 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108 public static final String ABBREV_MONTH_FORMAT = "%b";
109 public static final String NUMERIC_MONTH_FORMAT = "%m";
110 public static final String MONTH_DAY_FORMAT = "%-d";
111 public static final String YEAR_FORMAT = "%Y";
112 public static final String YEAR_FORMAT_TWO_DIGITS = "%g";
113 public static final String WEEKDAY_FORMAT = "%A";
114 public static final String ABBREV_WEEKDAY_FORMAT = "%a";
Jesse Wilson99a64f42011-11-11 10:56:05 -0500115
Elliott Hughesfbf37c72013-03-26 15:11:28 -0700116 /** @deprecated Do not use. */
Elliott Hughes6139e642013-07-24 14:46:31 -0700117 public static final int[] sameYearTable = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118
Elliott Hughesfbf37c72013-03-26 15:11:28 -0700119 /** @deprecated Do not use. */
Elliott Hughes6139e642013-07-24 14:46:31 -0700120 public static final int[] sameMonthTable = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121
122 /**
123 * Request the full spelled-out name. For use with the 'abbrev' parameter of
124 * {@link #getDayOfWeekString} and {@link #getMonthString}.
Jesse Wilson99a64f42011-11-11 10:56:05 -0500125 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800126 * @more <p>
127 * e.g. "Sunday" or "January"
Elliott Hughesfbf37c72013-03-26 15:11:28 -0700128 * @deprecated Use {@link java.text.SimpleDateFormat} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800129 */
Elliott Hughesd3c01012012-08-28 18:57:13 -0700130 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131 public static final int LENGTH_LONG = 10;
132
133 /**
134 * Request an abbreviated version of the name. For use with the 'abbrev'
135 * parameter of {@link #getDayOfWeekString} and {@link #getMonthString}.
Jesse Wilson99a64f42011-11-11 10:56:05 -0500136 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137 * @more <p>
138 * e.g. "Sun" or "Jan"
Elliott Hughesfbf37c72013-03-26 15:11:28 -0700139 * @deprecated Use {@link java.text.SimpleDateFormat} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800140 */
Elliott Hughesd3c01012012-08-28 18:57:13 -0700141 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142 public static final int LENGTH_MEDIUM = 20;
143
144 /**
145 * Request a shorter abbreviated version of the name.
146 * For use with the 'abbrev' parameter of {@link #getDayOfWeekString} and {@link #getMonthString}.
147 * @more
148 * <p>e.g. "Su" or "Jan"
Eric Fischer5bd644c2009-05-12 16:29:46 -0700149 * <p>In most languages, the results returned for LENGTH_SHORT will be the same as
150 * the results returned for {@link #LENGTH_MEDIUM}.
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_SHORT = 30;
155
156 /**
157 * Request an even shorter abbreviated version of the name.
Eric Fischer5bd644c2009-05-12 16:29:46 -0700158 * Do not use this. Currently this will always return the same result
159 * as {@link #LENGTH_SHORT}.
Elliott Hughesfbf37c72013-03-26 15:11:28 -0700160 * @deprecated Use {@link java.text.SimpleDateFormat} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161 */
Elliott Hughesd3c01012012-08-28 18:57:13 -0700162 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800163 public static final int LENGTH_SHORTER = 40;
164
165 /**
166 * Request an even shorter abbreviated version of the name.
167 * For use with the 'abbrev' parameter of {@link #getDayOfWeekString} and {@link #getMonthString}.
168 * @more
169 * <p>e.g. "S", "T", "T" or "J"
Eric Fischer5bd644c2009-05-12 16:29:46 -0700170 * <p>In some languages, the results returned for LENGTH_SHORTEST will be the same as
171 * the results returned for {@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_SHORTEST = 50;
176
177 /**
178 * Return a string for the day of the week.
179 * @param dayOfWeek One of {@link Calendar#SUNDAY Calendar.SUNDAY},
180 * {@link Calendar#MONDAY Calendar.MONDAY}, etc.
Eric Fischer5bd644c2009-05-12 16:29:46 -0700181 * @param abbrev One of {@link #LENGTH_LONG}, {@link #LENGTH_SHORT},
182 * {@link #LENGTH_MEDIUM}, or {@link #LENGTH_SHORTEST}.
183 * Note that in most languages, {@link #LENGTH_SHORT}
184 * will return the same as {@link #LENGTH_MEDIUM}.
185 * Undefined lengths will return {@link #LENGTH_MEDIUM}
186 * but may return something different in the future.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187 * @throws IndexOutOfBoundsException if the dayOfWeek is out of bounds.
Elliott Hughesfbf37c72013-03-26 15:11:28 -0700188 * @deprecated Use {@link java.text.SimpleDateFormat} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189 */
Elliott Hughesd3c01012012-08-28 18:57:13 -0700190 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191 public static String getDayOfWeekString(int dayOfWeek, int abbrev) {
Elliott Hughes08153ee2012-08-06 15:40:52 -0700192 LocaleData d = LocaleData.get(Locale.getDefault());
193 String[] names;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800194 switch (abbrev) {
Elliott Hughes08153ee2012-08-06 15:40:52 -0700195 case LENGTH_LONG: names = d.longWeekdayNames; break;
196 case LENGTH_MEDIUM: names = d.shortWeekdayNames; break;
197 case LENGTH_SHORT: names = d.shortWeekdayNames; break; // TODO
198 case LENGTH_SHORTER: names = d.shortWeekdayNames; break; // TODO
199 case LENGTH_SHORTEST: names = d.tinyWeekdayNames; break;
200 default: names = d.shortWeekdayNames; break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201 }
Elliott Hughes08153ee2012-08-06 15:40:52 -0700202 return names[dayOfWeek];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203 }
204
205 /**
206 * Return a localized string for AM or PM.
207 * @param ampm Either {@link Calendar#AM Calendar.AM} or {@link Calendar#PM Calendar.PM}.
208 * @throws IndexOutOfBoundsException if the ampm is out of bounds.
209 * @return Localized version of "AM" or "PM".
Elliott Hughesfbf37c72013-03-26 15:11:28 -0700210 * @deprecated Use {@link java.text.SimpleDateFormat} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211 */
Elliott Hughesd3c01012012-08-28 18:57:13 -0700212 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800213 public static String getAMPMString(int ampm) {
Elliott Hughes4af85342012-07-25 17:30:24 -0700214 return LocaleData.get(Locale.getDefault()).amPm[ampm - Calendar.AM];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800215 }
216
217 /**
Eric Fischer5bd644c2009-05-12 16:29:46 -0700218 * Return a localized string for the month of the year.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800219 * @param month One of {@link Calendar#JANUARY Calendar.JANUARY},
220 * {@link Calendar#FEBRUARY Calendar.FEBRUARY}, etc.
Eric Fischer5bd644c2009-05-12 16:29:46 -0700221 * @param abbrev One of {@link #LENGTH_LONG}, {@link #LENGTH_MEDIUM},
222 * or {@link #LENGTH_SHORTEST}.
223 * Undefined lengths will return {@link #LENGTH_MEDIUM}
224 * but may return something different in the future.
225 * @return Localized month of the year.
Elliott Hughesfbf37c72013-03-26 15:11:28 -0700226 * @deprecated Use {@link java.text.SimpleDateFormat} instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227 */
Elliott Hughesd3c01012012-08-28 18:57:13 -0700228 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229 public static String getMonthString(int month, int abbrev) {
Elliott Hughes08153ee2012-08-06 15:40:52 -0700230 LocaleData d = LocaleData.get(Locale.getDefault());
231 String[] names;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232 switch (abbrev) {
Elliott Hughes08153ee2012-08-06 15:40:52 -0700233 case LENGTH_LONG: names = d.longMonthNames; break;
234 case LENGTH_MEDIUM: names = d.shortMonthNames; break;
235 case LENGTH_SHORT: names = d.shortMonthNames; break;
236 case LENGTH_SHORTER: names = d.shortMonthNames; break;
237 case LENGTH_SHORTEST: names = d.tinyMonthNames; break;
238 default: names = d.shortMonthNames; break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239 }
Elliott Hughes08153ee2012-08-06 15:40:52 -0700240 return names[month];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241 }
242
243 /**
244 * Returns a string describing the elapsed time since startTime.
245 * @param startTime some time in the past.
246 * @return a String object containing the elapsed time.
247 * @see #getRelativeTimeSpanString(long, long, long)
248 */
249 public static CharSequence getRelativeTimeSpanString(long startTime) {
250 return getRelativeTimeSpanString(startTime, System.currentTimeMillis(), MINUTE_IN_MILLIS);
251 }
252
253 /**
254 * Returns a string describing 'time' as a time relative to 'now'.
255 * <p>
256 * Time spans in the past are formatted like "42 minutes ago".
257 * Time spans in the future are formatted like "in 42 minutes".
258 *
259 * @param time the time to describe, in milliseconds
260 * @param now the current time in milliseconds
261 * @param minResolution the minimum timespan to report. For example, a time 3 seconds in the
262 * past will be reported as "0 minutes ago" if this is set to MINUTE_IN_MILLIS. Pass one of
263 * 0, MINUTE_IN_MILLIS, HOUR_IN_MILLIS, DAY_IN_MILLIS, WEEK_IN_MILLIS
264 */
265 public static CharSequence getRelativeTimeSpanString(long time, long now, long minResolution) {
266 int flags = FORMAT_SHOW_DATE | FORMAT_SHOW_YEAR | FORMAT_ABBREV_MONTH;
267 return getRelativeTimeSpanString(time, now, minResolution, flags);
268 }
269
270 /**
271 * Returns a string describing 'time' as a time relative to 'now'.
272 * <p>
273 * Time spans in the past are formatted like "42 minutes ago". Time spans in
274 * the future are formatted like "in 42 minutes".
275 * <p>
276 * Can use {@link #FORMAT_ABBREV_RELATIVE} flag to use abbreviated relative
277 * times, like "42 mins ago".
Jesse Wilson99a64f42011-11-11 10:56:05 -0500278 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800279 * @param time the time to describe, in milliseconds
280 * @param now the current time in milliseconds
281 * @param minResolution the minimum timespan to report. For example, a time
282 * 3 seconds in the past will be reported as "0 minutes ago" if
283 * this is set to MINUTE_IN_MILLIS. Pass one of 0,
284 * MINUTE_IN_MILLIS, HOUR_IN_MILLIS, DAY_IN_MILLIS,
285 * WEEK_IN_MILLIS
286 * @param flags a bit mask of formatting options, such as
287 * {@link #FORMAT_NUMERIC_DATE} or
288 * {@link #FORMAT_ABBREV_RELATIVE}
289 */
290 public static CharSequence getRelativeTimeSpanString(long time, long now, long minResolution,
291 int flags) {
292 Resources r = Resources.getSystem();
293 boolean abbrevRelative = (flags & (FORMAT_ABBREV_RELATIVE | FORMAT_ABBREV_ALL)) != 0;
Jesse Wilson99a64f42011-11-11 10:56:05 -0500294
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800295 boolean past = (now >= time);
296 long duration = Math.abs(now - time);
297
298 int resId;
299 long count;
300 if (duration < MINUTE_IN_MILLIS && minResolution < MINUTE_IN_MILLIS) {
301 count = duration / SECOND_IN_MILLIS;
302 if (past) {
303 if (abbrevRelative) {
304 resId = com.android.internal.R.plurals.abbrev_num_seconds_ago;
305 } else {
306 resId = com.android.internal.R.plurals.num_seconds_ago;
307 }
308 } else {
309 if (abbrevRelative) {
310 resId = com.android.internal.R.plurals.abbrev_in_num_seconds;
311 } else {
312 resId = com.android.internal.R.plurals.in_num_seconds;
313 }
314 }
315 } else if (duration < HOUR_IN_MILLIS && minResolution < HOUR_IN_MILLIS) {
316 count = duration / MINUTE_IN_MILLIS;
317 if (past) {
318 if (abbrevRelative) {
319 resId = com.android.internal.R.plurals.abbrev_num_minutes_ago;
320 } else {
321 resId = com.android.internal.R.plurals.num_minutes_ago;
322 }
323 } else {
324 if (abbrevRelative) {
325 resId = com.android.internal.R.plurals.abbrev_in_num_minutes;
326 } else {
327 resId = com.android.internal.R.plurals.in_num_minutes;
328 }
329 }
330 } else if (duration < DAY_IN_MILLIS && minResolution < DAY_IN_MILLIS) {
331 count = duration / HOUR_IN_MILLIS;
332 if (past) {
333 if (abbrevRelative) {
334 resId = com.android.internal.R.plurals.abbrev_num_hours_ago;
335 } else {
336 resId = com.android.internal.R.plurals.num_hours_ago;
337 }
338 } else {
339 if (abbrevRelative) {
340 resId = com.android.internal.R.plurals.abbrev_in_num_hours;
341 } else {
342 resId = com.android.internal.R.plurals.in_num_hours;
343 }
344 }
345 } else if (duration < WEEK_IN_MILLIS && minResolution < WEEK_IN_MILLIS) {
Elliott Hughes5acc6e52013-03-07 16:46:55 -0800346 return getRelativeDayString(r, time, now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800347 } else {
348 // We know that we won't be showing the time, so it is safe to pass
349 // in a null context.
350 return formatDateRange(null, time, time, flags);
351 }
352
353 String format = r.getQuantityString(resId, (int) count);
354 return String.format(format, count);
355 }
Jesse Wilson99a64f42011-11-11 10:56:05 -0500356
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800357 /**
358 * Return string describing the elapsed time since startTime formatted like
359 * "[relative time/date], [time]".
360 * <p>
361 * Example output strings for the US date format.
362 * <ul>
363 * <li>3 mins ago, 10:15 AM</li>
364 * <li>yesterday, 12:20 PM</li>
365 * <li>Dec 12, 4:12 AM</li>
366 * <li>11/14/2007, 8:20 AM</li>
367 * </ul>
Jesse Wilson99a64f42011-11-11 10:56:05 -0500368 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800369 * @param time some time in the past.
370 * @param minResolution the minimum elapsed time (in milliseconds) to report
371 * when showing relative times. For example, a time 3 seconds in
372 * the past will be reported as "0 minutes ago" if this is set to
373 * {@link #MINUTE_IN_MILLIS}.
374 * @param transitionResolution the elapsed time (in milliseconds) at which
375 * to stop reporting relative measurements. Elapsed times greater
376 * than this resolution will default to normal date formatting.
377 * For example, will transition from "6 days ago" to "Dec 12"
378 * when using {@link #WEEK_IN_MILLIS}.
379 */
380 public static CharSequence getRelativeDateTimeString(Context c, long time, long minResolution,
381 long transitionResolution, int flags) {
382 Resources r = Resources.getSystem();
383
384 long now = System.currentTimeMillis();
385 long duration = Math.abs(now - time);
386
387 // getRelativeTimeSpanString() doesn't correctly format relative dates
388 // above a week or exact dates below a day, so clamp
389 // transitionResolution as needed.
390 if (transitionResolution > WEEK_IN_MILLIS) {
391 transitionResolution = WEEK_IN_MILLIS;
392 } else if (transitionResolution < DAY_IN_MILLIS) {
393 transitionResolution = DAY_IN_MILLIS;
394 }
395
396 CharSequence timeClause = formatDateRange(c, time, time, FORMAT_SHOW_TIME);
Jesse Wilson99a64f42011-11-11 10:56:05 -0500397
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800398 String result;
399 if (duration < transitionResolution) {
400 CharSequence relativeClause = getRelativeTimeSpanString(time, now, minResolution, flags);
401 result = r.getString(com.android.internal.R.string.relative_time, relativeClause, timeClause);
402 } else {
403 CharSequence dateClause = getRelativeTimeSpanString(c, time, false);
404 result = r.getString(com.android.internal.R.string.date_time, dateClause, timeClause);
405 }
406
407 return result;
408 }
409
410 /**
411 * Returns a string describing a day relative to the current day. For example if the day is
412 * today this function returns "Today", if the day was a week ago it returns "7 days ago", and
413 * if the day is in 2 weeks it returns "in 14 days".
Jesse Wilson99a64f42011-11-11 10:56:05 -0500414 *
Elliott Hughes5acc6e52013-03-07 16:46:55 -0800415 * @param r the resources
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800416 * @param day the relative day to describe in UTC milliseconds
417 * @param today the current time in UTC milliseconds
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800418 */
419 private static final String getRelativeDayString(Resources r, long day, long today) {
Elliott Hughes5acc6e52013-03-07 16:46:55 -0800420 Locale locale = r.getConfiguration().locale;
421 if (locale == null) {
422 locale = Locale.getDefault();
423 }
424
425 // TODO: use TimeZone.getOffset instead.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800426 Time startTime = new Time();
427 startTime.set(day);
Elliott Hughes5acc6e52013-03-07 16:46:55 -0800428 int startDay = Time.getJulianDay(day, startTime.gmtoff);
429
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800430 Time currentTime = new Time();
431 currentTime.set(today);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800432 int currentDay = Time.getJulianDay(today, currentTime.gmtoff);
433
434 int days = Math.abs(currentDay - startDay);
435 boolean past = (today > day);
Jesse Wilson99a64f42011-11-11 10:56:05 -0500436
Elliott Hughesc3ff72f2012-08-15 14:53:12 -0700437 // TODO: some locales name other days too, such as de_DE's "Vorgestern" (today - 2).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800438 if (days == 1) {
439 if (past) {
Elliott Hughesc3ff72f2012-08-15 14:53:12 -0700440 return LocaleData.get(locale).yesterday;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800441 } else {
Elliott Hughesc3ff72f2012-08-15 14:53:12 -0700442 return LocaleData.get(locale).tomorrow;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800443 }
444 } else if (days == 0) {
Elliott Hughesc3ff72f2012-08-15 14:53:12 -0700445 return LocaleData.get(locale).today;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800446 }
447
448 int resId;
449 if (past) {
450 resId = com.android.internal.R.plurals.num_days_ago;
451 } else {
452 resId = com.android.internal.R.plurals.in_num_days;
453 }
Jesse Wilson99a64f42011-11-11 10:56:05 -0500454
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800455 String format = r.getQuantityString(resId, days);
456 return String.format(format, days);
457 }
458
459 private static void initFormatStrings() {
460 synchronized (sLock) {
Jozef BABJAK25d8b052011-02-22 09:17:51 +0100461 initFormatStringsLocked();
462 }
463 }
464
465 private static void initFormatStringsLocked() {
466 Resources r = Resources.getSystem();
467 Configuration cfg = r.getConfiguration();
468 if (sLastConfig == null || !sLastConfig.equals(cfg)) {
469 sLastConfig = cfg;
Jozef BABJAK25d8b052011-02-22 09:17:51 +0100470 sElapsedFormatMMSS = r.getString(com.android.internal.R.string.elapsed_time_short_format_mm_ss);
471 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 -0800472 }
473 }
474
475 /**
Jeff Sharkey53f6e8a2012-11-13 16:23:59 -0800476 * Return given duration in a human-friendly format. For example, "4
477 * minutes" or "1 second". Returns only largest meaningful unit of time,
478 * from seconds up to hours.
479 *
480 * @hide
481 */
482 public static CharSequence formatDuration(long millis) {
483 final Resources res = Resources.getSystem();
484 if (millis >= HOUR_IN_MILLIS) {
485 final int hours = (int) ((millis + 1800000) / HOUR_IN_MILLIS);
486 return res.getQuantityString(
487 com.android.internal.R.plurals.duration_hours, hours, hours);
488 } else if (millis >= MINUTE_IN_MILLIS) {
489 final int minutes = (int) ((millis + 30000) / MINUTE_IN_MILLIS);
490 return res.getQuantityString(
491 com.android.internal.R.plurals.duration_minutes, minutes, minutes);
492 } else {
493 final int seconds = (int) ((millis + 500) / SECOND_IN_MILLIS);
494 return res.getQuantityString(
495 com.android.internal.R.plurals.duration_seconds, seconds, seconds);
496 }
497 }
498
499 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800500 * Formats an elapsed time in the form "MM:SS" or "H:MM:SS"
501 * for display on the call-in-progress screen.
502 * @param elapsedSeconds the elapsed time in seconds.
503 */
504 public static String formatElapsedTime(long elapsedSeconds) {
505 return formatElapsedTime(null, elapsedSeconds);
506 }
Jesse Wilson99a64f42011-11-11 10:56:05 -0500507
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800508 /**
Elliott Hughes2eda1842012-12-14 14:29:47 -0800509 * Formats an elapsed time in a format like "MM:SS" or "H:MM:SS" (using a form
510 * suited to the current locale), similar to that used on the call-in-progress
511 * screen.
Jesse Wilson99a64f42011-11-11 10:56:05 -0500512 *
Elliott Hughes2eda1842012-12-14 14:29:47 -0800513 * @param recycle {@link StringBuilder} to recycle, or null to use a temporary one.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800514 * @param elapsedSeconds the elapsed time in seconds.
515 */
516 public static String formatElapsedTime(StringBuilder recycle, long elapsedSeconds) {
Elliott Hughes2eda1842012-12-14 14:29:47 -0800517 // Break the elapsed seconds into hours, minutes, and seconds.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800518 long hours = 0;
519 long minutes = 0;
520 long seconds = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800521 if (elapsedSeconds >= 3600) {
522 hours = elapsedSeconds / 3600;
523 elapsedSeconds -= hours * 3600;
524 }
525 if (elapsedSeconds >= 60) {
526 minutes = elapsedSeconds / 60;
527 elapsedSeconds -= minutes * 60;
528 }
529 seconds = elapsedSeconds;
530
Elliott Hughes2eda1842012-12-14 14:29:47 -0800531 // Create a StringBuilder if we weren't given one to recycle.
532 // TODO: if we cared, we could have a thread-local temporary StringBuilder.
533 StringBuilder sb = recycle;
534 if (sb == null) {
535 sb = new StringBuilder(8);
536 } else {
537 sb.setLength(0);
538 }
539
540 // Format the broken-down time in a locale-appropriate way.
541 // TODO: use icu4c when http://unicode.org/cldr/trac/ticket/3407 is fixed.
542 Formatter f = new Formatter(sb, Locale.getDefault());
543 initFormatStrings();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800544 if (hours > 0) {
Elliott Hughes2eda1842012-12-14 14:29:47 -0800545 return f.format(sElapsedFormatHMMSS, hours, minutes, seconds).toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800546 } else {
Elliott Hughes2eda1842012-12-14 14:29:47 -0800547 return f.format(sElapsedFormatMMSS, minutes, seconds).toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800548 }
549 }
550
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800551 /**
552 * Format a date / time such that if the then is on the same day as now, it shows
553 * just the time and if it's a different day, it shows just the date.
Jesse Wilson99a64f42011-11-11 10:56:05 -0500554 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800555 * <p>The parameters dateFormat and timeFormat should each be one of
556 * {@link java.text.DateFormat#DEFAULT},
557 * {@link java.text.DateFormat#FULL},
558 * {@link java.text.DateFormat#LONG},
559 * {@link java.text.DateFormat#MEDIUM}
560 * or
561 * {@link java.text.DateFormat#SHORT}
562 *
563 * @param then the date to format
564 * @param now the base time
565 * @param dateStyle how to format the date portion.
566 * @param timeStyle how to format the time portion.
567 */
568 public static final CharSequence formatSameDayTime(long then, long now,
569 int dateStyle, int timeStyle) {
570 Calendar thenCal = new GregorianCalendar();
571 thenCal.setTimeInMillis(then);
572 Date thenDate = thenCal.getTime();
573 Calendar nowCal = new GregorianCalendar();
574 nowCal.setTimeInMillis(now);
575
576 java.text.DateFormat f;
577
578 if (thenCal.get(Calendar.YEAR) == nowCal.get(Calendar.YEAR)
579 && thenCal.get(Calendar.MONTH) == nowCal.get(Calendar.MONTH)
580 && thenCal.get(Calendar.DAY_OF_MONTH) == nowCal.get(Calendar.DAY_OF_MONTH)) {
581 f = java.text.DateFormat.getTimeInstance(timeStyle);
582 } else {
583 f = java.text.DateFormat.getDateInstance(dateStyle);
584 }
585 return f.format(thenDate);
586 }
587
588 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800589 * @return true if the supplied when is today else false
590 */
591 public static boolean isToday(long when) {
592 Time time = new Time();
593 time.set(when);
Jesse Wilson99a64f42011-11-11 10:56:05 -0500594
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800595 int thenYear = time.year;
596 int thenMonth = time.month;
597 int thenMonthDay = time.monthDay;
598
599 time.set(System.currentTimeMillis());
600 return (thenYear == time.year)
Jesse Wilson99a64f42011-11-11 10:56:05 -0500601 && (thenMonth == time.month)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800602 && (thenMonthDay == time.monthDay);
603 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800604
605 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800606 * Formats a date or a time range according to the local conventions.
Michael Chanbecfc9d2009-06-29 18:43:44 -0700607 * <p>
608 * Note that this is a convenience method. Using it involves creating an
609 * internal {@link java.util.Formatter} instance on-the-fly, which is
610 * somewhat costly in terms of memory and time. This is probably acceptable
611 * if you use the method only rarely, but if you rely on it for formatting a
612 * large number of dates, consider creating and reusing your own
613 * {@link java.util.Formatter} instance and use the version of
614 * {@link #formatDateRange(Context, long, long, int) formatDateRange}
615 * that takes a {@link java.util.Formatter}.
Erik577ec9e2010-09-01 17:24:53 -0700616 *
Michael Chanbecfc9d2009-06-29 18:43:44 -0700617 * @param context the context is required only if the time is shown
618 * @param startMillis the start time in UTC milliseconds
619 * @param endMillis the end time in UTC milliseconds
620 * @param flags a bit mask of options See
Erik577ec9e2010-09-01 17:24:53 -0700621 * {@link #formatDateRange(Context, Formatter, long, long, int, String) formatDateRange}
Michael Chanbecfc9d2009-06-29 18:43:44 -0700622 * @return a string containing the formatted date/time range.
623 */
624 public static String formatDateRange(Context context, long startMillis,
625 long endMillis, int flags) {
626 Formatter f = new Formatter(new StringBuilder(50), Locale.getDefault());
627 return formatDateRange(context, f, startMillis, endMillis, flags).toString();
628 }
629
630 /**
631 * Formats a date or a time range according to the local conventions.
Erik577ec9e2010-09-01 17:24:53 -0700632 * <p>
633 * Note that this is a convenience method for formatting the date or
634 * time range in the local time zone. If you want to specify the time
635 * zone please use
636 * {@link #formatDateRange(Context, Formatter, long, long, int, String) formatDateRange}.
637 *
638 * @param context the context is required only if the time is shown
639 * @param formatter the Formatter used for formatting the date range.
640 * Note: be sure to call setLength(0) on StringBuilder passed to
641 * the Formatter constructor unless you want the results to accumulate.
642 * @param startMillis the start time in UTC milliseconds
643 * @param endMillis the end time in UTC milliseconds
644 * @param flags a bit mask of options See
645 * {@link #formatDateRange(Context, Formatter, long, long, int, String) formatDateRange}
646 * @return a string containing the formatted date/time range.
647 */
648 public static Formatter formatDateRange(Context context, Formatter formatter, long startMillis,
649 long endMillis, int flags) {
650 return formatDateRange(context, formatter, startMillis, endMillis, flags, null);
651 }
652
653 /**
654 * Formats a date or a time range according to the local conventions.
Jesse Wilson99a64f42011-11-11 10:56:05 -0500655 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800656 * <p>
657 * Example output strings (date formats in these examples are shown using
658 * the US date format convention but that may change depending on the
659 * local settings):
660 * <ul>
661 * <li>10:15am</li>
662 * <li>3:00pm - 4:00pm</li>
663 * <li>3pm - 4pm</li>
664 * <li>3PM - 4PM</li>
665 * <li>08:00 - 17:00</li>
666 * <li>Oct 9</li>
667 * <li>Tue, Oct 9</li>
668 * <li>October 9, 2007</li>
669 * <li>Oct 9 - 10</li>
670 * <li>Oct 9 - 10, 2007</li>
671 * <li>Oct 28 - Nov 3, 2007</li>
672 * <li>Dec 31, 2007 - Jan 1, 2008</li>
673 * <li>Oct 9, 8:00am - Oct 10, 5:00pm</li>
674 * <li>12/31/2007 - 01/01/2008</li>
675 * </ul>
Jesse Wilson99a64f42011-11-11 10:56:05 -0500676 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800677 * <p>
678 * The flags argument is a bitmask of options from the following list:
Jesse Wilson99a64f42011-11-11 10:56:05 -0500679 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800680 * <ul>
681 * <li>FORMAT_SHOW_TIME</li>
682 * <li>FORMAT_SHOW_WEEKDAY</li>
683 * <li>FORMAT_SHOW_YEAR</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800684 * <li>FORMAT_SHOW_DATE</li>
685 * <li>FORMAT_NO_MONTH_DAY</li>
686 * <li>FORMAT_12HOUR</li>
687 * <li>FORMAT_24HOUR</li>
688 * <li>FORMAT_CAP_AMPM</li>
689 * <li>FORMAT_NO_NOON</li>
690 * <li>FORMAT_CAP_NOON</li>
691 * <li>FORMAT_NO_MIDNIGHT</li>
692 * <li>FORMAT_CAP_MIDNIGHT</li>
693 * <li>FORMAT_UTC</li>
694 * <li>FORMAT_ABBREV_TIME</li>
695 * <li>FORMAT_ABBREV_WEEKDAY</li>
696 * <li>FORMAT_ABBREV_MONTH</li>
697 * <li>FORMAT_ABBREV_ALL</li>
698 * <li>FORMAT_NUMERIC_DATE</li>
699 * </ul>
Jesse Wilson99a64f42011-11-11 10:56:05 -0500700 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800701 * <p>
702 * If FORMAT_SHOW_TIME is set, the time is shown as part of the date range.
703 * If the start and end time are the same, then just the start time is
704 * shown.
Jesse Wilson99a64f42011-11-11 10:56:05 -0500705 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800706 * <p>
707 * If FORMAT_SHOW_WEEKDAY is set, then the weekday is shown.
Jesse Wilson99a64f42011-11-11 10:56:05 -0500708 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800709 * <p>
710 * If FORMAT_SHOW_YEAR is set, then the year is always shown.
Elliott Hughes6139e642013-07-24 14:46:31 -0700711 * If FORMAT_SHOW_YEAR is not set, then the year
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800712 * is shown only if it is different from the current year, or if the start
Elliott Hughes6139e642013-07-24 14:46:31 -0700713 * and end dates fall on different years.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800714 *
715 * <p>
716 * Normally the date is shown unless the start and end day are the same.
717 * If FORMAT_SHOW_DATE is set, then the date is always shown, even for
718 * same day ranges.
Jesse Wilson99a64f42011-11-11 10:56:05 -0500719 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800720 * <p>
721 * If FORMAT_NO_MONTH_DAY is set, then if the date is shown, just the
722 * month name will be shown, not the day of the month. For example,
723 * "January, 2008" instead of "January 6 - 12, 2008".
Jesse Wilson99a64f42011-11-11 10:56:05 -0500724 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800725 * <p>
726 * If FORMAT_CAP_AMPM is set and 12-hour time is used, then the "AM"
Eric Fischer84c863d2009-06-10 12:10:22 -0700727 * and "PM" are capitalized. You should not use this flag
728 * because in some locales these terms cannot be capitalized, and in
729 * many others it doesn't make sense to do so even though it is possible.
Jesse Wilson99a64f42011-11-11 10:56:05 -0500730 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800731 * <p>
732 * If FORMAT_NO_NOON is set and 12-hour time is used, then "12pm" is
733 * shown instead of "noon".
Jesse Wilson99a64f42011-11-11 10:56:05 -0500734 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800735 * <p>
736 * If FORMAT_CAP_NOON is set and 12-hour time is used, then "Noon" is
Eric Fischer84c863d2009-06-10 12:10:22 -0700737 * shown instead of "noon". You should probably not use this flag
738 * because in many locales it will not make sense to capitalize
739 * the term.
Jesse Wilson99a64f42011-11-11 10:56:05 -0500740 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800741 * <p>
742 * If FORMAT_NO_MIDNIGHT is set and 12-hour time is used, then "12am" is
743 * shown instead of "midnight".
Jesse Wilson99a64f42011-11-11 10:56:05 -0500744 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800745 * <p>
Eric Fischer84c863d2009-06-10 12:10:22 -0700746 * If FORMAT_CAP_MIDNIGHT is set and 12-hour time is used, then "Midnight"
747 * is shown instead of "midnight". You should probably not use this
748 * flag because in many locales it will not make sense to capitalize
749 * the term.
Jesse Wilson99a64f42011-11-11 10:56:05 -0500750 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800751 * <p>
752 * If FORMAT_12HOUR is set and the time is shown, then the time is
753 * shown in the 12-hour time format. You should not normally set this.
754 * Instead, let the time format be chosen automatically according to the
755 * system settings. If both FORMAT_12HOUR and FORMAT_24HOUR are set, then
756 * FORMAT_24HOUR takes precedence.
Jesse Wilson99a64f42011-11-11 10:56:05 -0500757 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800758 * <p>
759 * If FORMAT_24HOUR is set and the time is shown, then the time is
760 * shown in the 24-hour time format. You should not normally set this.
761 * Instead, let the time format be chosen automatically according to the
762 * system settings. If both FORMAT_12HOUR and FORMAT_24HOUR are set, then
763 * FORMAT_24HOUR takes precedence.
Jesse Wilson99a64f42011-11-11 10:56:05 -0500764 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765 * <p>
Erik577ec9e2010-09-01 17:24:53 -0700766 * If FORMAT_UTC is set, then the UTC time zone is used for the start
767 * and end milliseconds unless a time zone is specified. If a time zone
768 * is specified it will be used regardless of the FORMAT_UTC flag.
Jesse Wilson99a64f42011-11-11 10:56:05 -0500769 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800770 * <p>
771 * If FORMAT_ABBREV_TIME is set and 12-hour time format is used, then the
772 * start and end times (if shown) are abbreviated by not showing the minutes
773 * if they are zero. For example, instead of "3:00pm" the time would be
774 * abbreviated to "3pm".
Jesse Wilson99a64f42011-11-11 10:56:05 -0500775 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800776 * <p>
777 * If FORMAT_ABBREV_WEEKDAY is set, then the weekday (if shown) is
778 * abbreviated to a 3-letter string.
Jesse Wilson99a64f42011-11-11 10:56:05 -0500779 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800780 * <p>
781 * If FORMAT_ABBREV_MONTH is set, then the month (if shown) is abbreviated
782 * to a 3-letter string.
Jesse Wilson99a64f42011-11-11 10:56:05 -0500783 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800784 * <p>
785 * If FORMAT_ABBREV_ALL is set, then the weekday and the month (if shown)
786 * are abbreviated to 3-letter strings.
Jesse Wilson99a64f42011-11-11 10:56:05 -0500787 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800788 * <p>
789 * If FORMAT_NUMERIC_DATE is set, then the date is shown in numeric format
790 * instead of using the name of the month. For example, "12/31/2008"
791 * instead of "December 31, 2008".
Jesse Wilson99a64f42011-11-11 10:56:05 -0500792 *
793 * <p>
794 * If the end date ends at 12:00am at the beginning of a day, it is
795 * formatted as the end of the previous day in two scenarios:
796 * <ul>
797 * <li>For single day events. This results in "8pm - midnight" instead of
798 * "Nov 10, 8pm - Nov 11, 12am".</li>
799 * <li>When the time is not displayed. This results in "Nov 10 - 11" for
800 * an event with a start date of Nov 10 and an end date of Nov 12 at
801 * 00:00.</li>
802 * </ul>
803 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800804 * @param context the context is required only if the time is shown
Michael Chanbecfc9d2009-06-29 18:43:44 -0700805 * @param formatter the Formatter used for formatting the date range.
806 * Note: be sure to call setLength(0) on StringBuilder passed to
807 * the Formatter constructor unless you want the results to accumulate.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800808 * @param startMillis the start time in UTC milliseconds
809 * @param endMillis the end time in UTC milliseconds
810 * @param flags a bit mask of options
Erik577ec9e2010-09-01 17:24:53 -0700811 * @param timeZone the time zone to compute the string in. Use null for local
812 * or if the FORMAT_UTC flag is being used.
Jesse Wilson99a64f42011-11-11 10:56:05 -0500813 *
Michael Chanbecfc9d2009-06-29 18:43:44 -0700814 * @return the formatter with the formatted date/time range appended to the string buffer.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800815 */
Michael Chanbecfc9d2009-06-29 18:43:44 -0700816 public static Formatter formatDateRange(Context context, Formatter formatter, long startMillis,
Elliott Hughesf0b79ae2013-08-14 15:12:43 -0700817 long endMillis, int flags, String timeZone) {
Elliott Hughes8d8ef002013-08-16 11:56:35 -0700818 // If we're being asked to format a time without being explicitly told whether to use
819 // 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 -0700820 // but we want to fall back to the user's preference.
Elliott Hughes8d8ef002013-08-16 11:56:35 -0700821 if ((flags & (FORMAT_SHOW_TIME | FORMAT_12HOUR | FORMAT_24HOUR)) == FORMAT_SHOW_TIME) {
Elliott Hughesf0b79ae2013-08-14 15:12:43 -0700822 flags |= DateFormat.is24HourFormat(context) ? FORMAT_24HOUR : FORMAT_12HOUR;
823 }
824
Elliott Hughes6139e642013-07-24 14:46:31 -0700825 String range = DateIntervalFormat.formatDateRange(startMillis, endMillis, flags, timeZone);
826 try {
827 formatter.out().append(range);
828 } catch (IOException impossible) {
829 throw new AssertionError(impossible);
Erik577ec9e2010-09-01 17:24:53 -0700830 }
Elliott Hughes6139e642013-07-24 14:46:31 -0700831 return formatter;
Sungmin Choi9a2ada42013-02-28 20:17:15 +0900832 }
833
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834 /**
835 * Formats a date or a time according to the local conventions. There are
836 * lots of options that allow the caller to control, for example, if the
837 * time is shown, if the day of the week is shown, if the month name is
838 * abbreviated, if noon is shown instead of 12pm, and so on. For the
839 * complete list of options, see the documentation for
840 * {@link #formatDateRange}.
841 * <p>
842 * Example output strings (date formats in these examples are shown using
843 * the US date format convention but that may change depending on the
844 * local settings):
845 * <ul>
846 * <li>10:15am</li>
847 * <li>3:00pm</li>
848 * <li>3pm</li>
849 * <li>3PM</li>
850 * <li>08:00</li>
851 * <li>17:00</li>
852 * <li>noon</li>
853 * <li>Noon</li>
854 * <li>midnight</li>
855 * <li>Midnight</li>
856 * <li>Oct 31</li>
857 * <li>Oct 31, 2007</li>
858 * <li>October 31, 2007</li>
859 * <li>10am, Oct 31</li>
860 * <li>17:00, Oct 31</li>
861 * <li>Wed</li>
862 * <li>Wednesday</li>
863 * <li>10am, Wed, Oct 31</li>
864 * <li>Wed, Oct 31</li>
865 * <li>Wednesday, Oct 31</li>
866 * <li>Wed, Oct 31, 2007</li>
867 * <li>Wed, October 31</li>
868 * <li>10/31/2007</li>
869 * </ul>
Jesse Wilson99a64f42011-11-11 10:56:05 -0500870 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800871 * @param context the context is required only if the time is shown
872 * @param millis a point in time in UTC milliseconds
873 * @param flags a bit mask of formatting options
874 * @return a string containing the formatted date/time.
875 */
876 public static String formatDateTime(Context context, long millis, int flags) {
877 return formatDateRange(context, millis, millis, flags);
878 }
879
880 /**
881 * @return a relative time string to display the time expressed by millis. Times
882 * are counted starting at midnight, which means that assuming that the current
883 * time is March 31st, 0:30:
884 * <ul>
Jesse Wilson99a64f42011-11-11 10:56:05 -0500885 * <li>"millis=0:10 today" will be displayed as "0:10"</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886 * <li>"millis=11:30pm the day before" will be displayed as "Mar 30"</li>
887 * </ul>
888 * If the given millis is in a different year, then the full date is
889 * returned in numeric format (e.g., "10/12/2008").
Jesse Wilson99a64f42011-11-11 10:56:05 -0500890 *
891 * @param withPreposition If true, the string returned will include the correct
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800892 * preposition ("at 9:20am", "on 10/12/2008" or "on May 29").
893 */
894 public static CharSequence getRelativeTimeSpanString(Context c, long millis,
895 boolean withPreposition) {
896
David Sobreira Marques6a84af02010-03-28 19:39:17 -0300897 String result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800898 long now = System.currentTimeMillis();
Steve Pomeroyca336372012-08-27 02:20:13 -0400899 long span = Math.abs(now - millis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800900
David Sobreira Marques6a84af02010-03-28 19:39:17 -0300901 synchronized (DateUtils.class) {
902 if (sNowTime == null) {
903 sNowTime = new Time();
904 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800905
David Sobreira Marques6a84af02010-03-28 19:39:17 -0300906 if (sThenTime == null) {
907 sThenTime = new Time();
908 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800909
David Sobreira Marques6a84af02010-03-28 19:39:17 -0300910 sNowTime.set(now);
911 sThenTime.set(millis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800912
David Sobreira Marques6a84af02010-03-28 19:39:17 -0300913 int prepositionId;
914 if (span < DAY_IN_MILLIS && sNowTime.weekDay == sThenTime.weekDay) {
915 // Same day
916 int flags = FORMAT_SHOW_TIME;
917 result = formatDateRange(c, millis, millis, flags);
918 prepositionId = R.string.preposition_for_time;
919 } else if (sNowTime.year != sThenTime.year) {
920 // Different years
921 int flags = FORMAT_SHOW_DATE | FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE;
922 result = formatDateRange(c, millis, millis, flags);
923
924 // This is a date (like "10/31/2008" so use the date preposition)
925 prepositionId = R.string.preposition_for_date;
926 } else {
927 // Default
928 int flags = FORMAT_SHOW_DATE | FORMAT_ABBREV_MONTH;
929 result = formatDateRange(c, millis, millis, flags);
930 prepositionId = R.string.preposition_for_date;
931 }
932 if (withPreposition) {
933 Resources res = c.getResources();
934 result = res.getString(prepositionId, result);
935 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800936 }
937 return result;
938 }
Jesse Wilson99a64f42011-11-11 10:56:05 -0500939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800940 /**
Jesse Wilson99a64f42011-11-11 10:56:05 -0500941 * Convenience function to return relative time string without preposition.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800942 * @param c context for resources
943 * @param millis time in milliseconds
944 * @return {@link CharSequence} containing relative time.
945 * @see #getRelativeTimeSpanString(Context, long, boolean)
946 */
947 public static CharSequence getRelativeTimeSpanString(Context c, long millis) {
948 return getRelativeTimeSpanString(c, millis, false /* no preposition */);
949 }
Jesse Wilson99a64f42011-11-11 10:56:05 -0500950
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800951 private static Time sNowTime;
952 private static Time sThenTime;
953}