DateUtils.java revision 5bd644caf73e76750feef1a82b8817d32f5367fc
1/*
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;
24import android.pim.DateException;
25
26import java.util.Calendar;
27import java.util.Date;
28import java.util.GregorianCalendar;
29import java.util.TimeZone;
30
31/**
32 * This class contains various date-related utilities for creating text for things like
33 * elapsed time and date ranges, strings for days of the week and months, and AM/PM text etc.
34 */
35public class DateUtils
36{
37    private static final Object sLock = new Object();
38    private static final int[] sDaysLong = new int[] {
39            com.android.internal.R.string.day_of_week_long_sunday,
40            com.android.internal.R.string.day_of_week_long_monday,
41            com.android.internal.R.string.day_of_week_long_tuesday,
42            com.android.internal.R.string.day_of_week_long_wednesday,
43            com.android.internal.R.string.day_of_week_long_thursday,
44            com.android.internal.R.string.day_of_week_long_friday,
45            com.android.internal.R.string.day_of_week_long_saturday,
46        };
47    private static final int[] sDaysMedium = new int[] {
48            com.android.internal.R.string.day_of_week_medium_sunday,
49            com.android.internal.R.string.day_of_week_medium_monday,
50            com.android.internal.R.string.day_of_week_medium_tuesday,
51            com.android.internal.R.string.day_of_week_medium_wednesday,
52            com.android.internal.R.string.day_of_week_medium_thursday,
53            com.android.internal.R.string.day_of_week_medium_friday,
54            com.android.internal.R.string.day_of_week_medium_saturday,
55        };
56    private static final int[] sDaysShort = new int[] {
57            com.android.internal.R.string.day_of_week_short_sunday,
58            com.android.internal.R.string.day_of_week_short_monday,
59            com.android.internal.R.string.day_of_week_short_tuesday,
60            com.android.internal.R.string.day_of_week_short_wednesday,
61            com.android.internal.R.string.day_of_week_short_thursday,
62            com.android.internal.R.string.day_of_week_short_friday,
63            com.android.internal.R.string.day_of_week_short_saturday,
64        };
65    private static final int[] sDaysShortest = new int[] {
66            com.android.internal.R.string.day_of_week_shortest_sunday,
67            com.android.internal.R.string.day_of_week_shortest_monday,
68            com.android.internal.R.string.day_of_week_shortest_tuesday,
69            com.android.internal.R.string.day_of_week_shortest_wednesday,
70            com.android.internal.R.string.day_of_week_shortest_thursday,
71            com.android.internal.R.string.day_of_week_shortest_friday,
72            com.android.internal.R.string.day_of_week_shortest_saturday,
73        };
74    private static final int[] sMonthsStandaloneLong = new int [] {
75            com.android.internal.R.string.month_long_standalone_january,
76            com.android.internal.R.string.month_long_standalone_february,
77            com.android.internal.R.string.month_long_standalone_march,
78            com.android.internal.R.string.month_long_standalone_april,
79            com.android.internal.R.string.month_long_standalone_may,
80            com.android.internal.R.string.month_long_standalone_june,
81            com.android.internal.R.string.month_long_standalone_july,
82            com.android.internal.R.string.month_long_standalone_august,
83            com.android.internal.R.string.month_long_standalone_september,
84            com.android.internal.R.string.month_long_standalone_october,
85            com.android.internal.R.string.month_long_standalone_november,
86            com.android.internal.R.string.month_long_standalone_december,
87        };
88    private static final int[] sMonthsLong = new int [] {
89            com.android.internal.R.string.month_long_january,
90            com.android.internal.R.string.month_long_february,
91            com.android.internal.R.string.month_long_march,
92            com.android.internal.R.string.month_long_april,
93            com.android.internal.R.string.month_long_may,
94            com.android.internal.R.string.month_long_june,
95            com.android.internal.R.string.month_long_july,
96            com.android.internal.R.string.month_long_august,
97            com.android.internal.R.string.month_long_september,
98            com.android.internal.R.string.month_long_october,
99            com.android.internal.R.string.month_long_november,
100            com.android.internal.R.string.month_long_december,
101        };
102    private static final int[] sMonthsMedium = new int [] {
103            com.android.internal.R.string.month_medium_january,
104            com.android.internal.R.string.month_medium_february,
105            com.android.internal.R.string.month_medium_march,
106            com.android.internal.R.string.month_medium_april,
107            com.android.internal.R.string.month_medium_may,
108            com.android.internal.R.string.month_medium_june,
109            com.android.internal.R.string.month_medium_july,
110            com.android.internal.R.string.month_medium_august,
111            com.android.internal.R.string.month_medium_september,
112            com.android.internal.R.string.month_medium_october,
113            com.android.internal.R.string.month_medium_november,
114            com.android.internal.R.string.month_medium_december,
115        };
116    private static final int[] sMonthsShortest = new int [] {
117            com.android.internal.R.string.month_shortest_january,
118            com.android.internal.R.string.month_shortest_february,
119            com.android.internal.R.string.month_shortest_march,
120            com.android.internal.R.string.month_shortest_april,
121            com.android.internal.R.string.month_shortest_may,
122            com.android.internal.R.string.month_shortest_june,
123            com.android.internal.R.string.month_shortest_july,
124            com.android.internal.R.string.month_shortest_august,
125            com.android.internal.R.string.month_shortest_september,
126            com.android.internal.R.string.month_shortest_october,
127            com.android.internal.R.string.month_shortest_november,
128            com.android.internal.R.string.month_shortest_december,
129        };
130    private static final int[] sAmPm = new int[] {
131            com.android.internal.R.string.am,
132            com.android.internal.R.string.pm,
133        };
134    private static Configuration sLastConfig;
135    private static java.text.DateFormat sStatusTimeFormat;
136    private static String sElapsedFormatMMSS;
137    private static String sElapsedFormatHMMSS;
138
139    private static final String FAST_FORMAT_HMMSS = "%1$d:%2$02d:%3$02d";
140    private static final String FAST_FORMAT_MMSS = "%1$02d:%2$02d";
141    private static final char TIME_PADDING = '0';
142    private static final char TIME_SEPARATOR = ':';
143
144
145    public static final long SECOND_IN_MILLIS = 1000;
146    public static final long MINUTE_IN_MILLIS = SECOND_IN_MILLIS * 60;
147    public static final long HOUR_IN_MILLIS = MINUTE_IN_MILLIS * 60;
148    public static final long DAY_IN_MILLIS = HOUR_IN_MILLIS * 24;
149    public static final long WEEK_IN_MILLIS = DAY_IN_MILLIS * 7;
150    public static final long YEAR_IN_MILLIS = WEEK_IN_MILLIS * 52;
151
152    // The following FORMAT_* symbols are used for specifying the format of
153    // dates and times in the formatDateRange method.
154    public static final int FORMAT_SHOW_TIME = 0x00001;
155    public static final int FORMAT_SHOW_WEEKDAY = 0x00002;
156    public static final int FORMAT_SHOW_YEAR = 0x00004;
157    public static final int FORMAT_NO_YEAR = 0x00008;
158    public static final int FORMAT_SHOW_DATE = 0x00010;
159    public static final int FORMAT_NO_MONTH_DAY = 0x00020;
160    public static final int FORMAT_12HOUR = 0x00040;
161    public static final int FORMAT_24HOUR = 0x00080;
162    public static final int FORMAT_CAP_AMPM = 0x00100;
163    public static final int FORMAT_NO_NOON = 0x00200;
164    public static final int FORMAT_CAP_NOON = 0x00400;
165    public static final int FORMAT_NO_MIDNIGHT = 0x00800;
166    public static final int FORMAT_CAP_MIDNIGHT = 0x01000;
167    public static final int FORMAT_UTC = 0x02000;
168    public static final int FORMAT_ABBREV_TIME = 0x04000;
169    public static final int FORMAT_ABBREV_WEEKDAY = 0x08000;
170    public static final int FORMAT_ABBREV_MONTH = 0x10000;
171    public static final int FORMAT_NUMERIC_DATE = 0x20000;
172    public static final int FORMAT_ABBREV_RELATIVE = 0x40000;
173    public static final int FORMAT_ABBREV_ALL = 0x80000;
174    public static final int FORMAT_CAP_NOON_MIDNIGHT = (FORMAT_CAP_NOON | FORMAT_CAP_MIDNIGHT);
175    public static final int FORMAT_NO_NOON_MIDNIGHT = (FORMAT_NO_NOON | FORMAT_NO_MIDNIGHT);
176
177    // Date and time format strings that are constant and don't need to be
178    // translated.
179    public static final String HOUR_MINUTE_24 = "%H:%M";
180    public static final String MONTH_FORMAT = "%B";
181    public static final String ABBREV_MONTH_FORMAT = "%b";
182    public static final String NUMERIC_MONTH_FORMAT = "%m";
183    public static final String MONTH_DAY_FORMAT = "%-d";
184    public static final String YEAR_FORMAT = "%Y";
185    public static final String YEAR_FORMAT_TWO_DIGITS = "%g";
186    public static final String WEEKDAY_FORMAT = "%A";
187    public static final String ABBREV_WEEKDAY_FORMAT = "%a";
188
189    // This table is used to lookup the resource string id of a format string
190    // used for formatting a start and end date that fall in the same year.
191    // The index is constructed from a bit-wise OR of the boolean values:
192    // {showTime, showYear, showWeekDay}.  For example, if showYear and
193    // showWeekDay are both true, then the index would be 3.
194    public static final int sameYearTable[] = {
195        com.android.internal.R.string.same_year_md1_md2,
196        com.android.internal.R.string.same_year_wday1_md1_wday2_md2,
197        com.android.internal.R.string.same_year_mdy1_mdy2,
198        com.android.internal.R.string.same_year_wday1_mdy1_wday2_mdy2,
199        com.android.internal.R.string.same_year_md1_time1_md2_time2,
200        com.android.internal.R.string.same_year_wday1_md1_time1_wday2_md2_time2,
201        com.android.internal.R.string.same_year_mdy1_time1_mdy2_time2,
202        com.android.internal.R.string.same_year_wday1_mdy1_time1_wday2_mdy2_time2,
203
204        // Numeric date strings
205        com.android.internal.R.string.numeric_md1_md2,
206        com.android.internal.R.string.numeric_wday1_md1_wday2_md2,
207        com.android.internal.R.string.numeric_mdy1_mdy2,
208        com.android.internal.R.string.numeric_wday1_mdy1_wday2_mdy2,
209        com.android.internal.R.string.numeric_md1_time1_md2_time2,
210        com.android.internal.R.string.numeric_wday1_md1_time1_wday2_md2_time2,
211        com.android.internal.R.string.numeric_mdy1_time1_mdy2_time2,
212        com.android.internal.R.string.numeric_wday1_mdy1_time1_wday2_mdy2_time2,
213    };
214
215    // This table is used to lookup the resource string id of a format string
216    // used for formatting a start and end date that fall in the same month.
217    // The index is constructed from a bit-wise OR of the boolean values:
218    // {showTime, showYear, showWeekDay}.  For example, if showYear and
219    // showWeekDay are both true, then the index would be 3.
220    public static final int sameMonthTable[] = {
221        com.android.internal.R.string.same_month_md1_md2,
222        com.android.internal.R.string.same_month_wday1_md1_wday2_md2,
223        com.android.internal.R.string.same_month_mdy1_mdy2,
224        com.android.internal.R.string.same_month_wday1_mdy1_wday2_mdy2,
225        com.android.internal.R.string.same_month_md1_time1_md2_time2,
226        com.android.internal.R.string.same_month_wday1_md1_time1_wday2_md2_time2,
227        com.android.internal.R.string.same_month_mdy1_time1_mdy2_time2,
228        com.android.internal.R.string.same_month_wday1_mdy1_time1_wday2_mdy2_time2,
229
230        com.android.internal.R.string.numeric_md1_md2,
231        com.android.internal.R.string.numeric_wday1_md1_wday2_md2,
232        com.android.internal.R.string.numeric_mdy1_mdy2,
233        com.android.internal.R.string.numeric_wday1_mdy1_wday2_mdy2,
234        com.android.internal.R.string.numeric_md1_time1_md2_time2,
235        com.android.internal.R.string.numeric_wday1_md1_time1_wday2_md2_time2,
236        com.android.internal.R.string.numeric_mdy1_time1_mdy2_time2,
237        com.android.internal.R.string.numeric_wday1_mdy1_time1_wday2_mdy2_time2,
238    };
239
240    /**
241     * Request the full spelled-out name. For use with the 'abbrev' parameter of
242     * {@link #getDayOfWeekString} and {@link #getMonthString}.
243     *
244     * @more <p>
245     *       e.g. "Sunday" or "January"
246     */
247    public static final int LENGTH_LONG = 10;
248
249    /**
250     * Request an abbreviated version of the name. For use with the 'abbrev'
251     * parameter of {@link #getDayOfWeekString} and {@link #getMonthString}.
252     *
253     * @more <p>
254     *       e.g. "Sun" or "Jan"
255     */
256    public static final int LENGTH_MEDIUM = 20;
257
258    /**
259     * Request a shorter abbreviated version of the name.
260     * For use with the 'abbrev' parameter of {@link #getDayOfWeekString} and {@link #getMonthString}.
261     * @more
262     * <p>e.g. "Su" or "Jan"
263     * <p>In most languages, the results returned for LENGTH_SHORT will be the same as
264     * the results returned for {@link #LENGTH_MEDIUM}.
265     */
266    public static final int LENGTH_SHORT = 30;
267
268    /**
269     * Request an even shorter abbreviated version of the name.
270     * Do not use this.  Currently this will always return the same result
271     * as {@link #LENGTH_SHORT}.
272     */
273    public static final int LENGTH_SHORTER = 40;
274
275    /**
276     * Request an even shorter abbreviated version of the name.
277     * For use with the 'abbrev' parameter of {@link #getDayOfWeekString} and {@link #getMonthString}.
278     * @more
279     * <p>e.g. "S", "T", "T" or "J"
280     * <p>In some languages, the results returned for LENGTH_SHORTEST will be the same as
281     * the results returned for {@link #LENGTH_SHORT}.
282     */
283    public static final int LENGTH_SHORTEST = 50;
284
285    /**
286     * Return a string for the day of the week.
287     * @param dayOfWeek One of {@link Calendar#SUNDAY Calendar.SUNDAY},
288     *               {@link Calendar#MONDAY Calendar.MONDAY}, etc.
289     * @param abbrev One of {@link #LENGTH_LONG}, {@link #LENGTH_SHORT},
290     *               {@link #LENGTH_MEDIUM}, or {@link #LENGTH_SHORTEST}.
291     *               Note that in most languages, {@link #LENGTH_SHORT}
292     *               will return the same as {@link #LENGTH_MEDIUM}.
293     *               Undefined lengths will return {@link #LENGTH_MEDIUM}
294     *               but may return something different in the future.
295     * @throws IndexOutOfBoundsException if the dayOfWeek is out of bounds.
296     */
297    public static String getDayOfWeekString(int dayOfWeek, int abbrev) {
298        int[] list;
299        switch (abbrev) {
300            case LENGTH_LONG:       list = sDaysLong;       break;
301            case LENGTH_MEDIUM:     list = sDaysMedium;     break;
302            case LENGTH_SHORT:      list = sDaysShort;      break;
303            case LENGTH_SHORTER:    list = sDaysShort;      break;
304            case LENGTH_SHORTEST:   list = sDaysShortest;   break;
305            default:                list = sDaysMedium;     break;
306        }
307
308        Resources r = Resources.getSystem();
309        return r.getString(list[dayOfWeek - Calendar.SUNDAY]);
310    }
311
312    /**
313     * Return a localized string for AM or PM.
314     * @param ampm Either {@link Calendar#AM Calendar.AM} or {@link Calendar#PM Calendar.PM}.
315     * @throws IndexOutOfBoundsException if the ampm is out of bounds.
316     * @return Localized version of "AM" or "PM".
317     */
318    public static String getAMPMString(int ampm) {
319        Resources r = Resources.getSystem();
320        return r.getString(sAmPm[ampm - Calendar.AM]);
321    }
322
323    /**
324     * Return a localized string for the month of the year.
325     * @param month One of {@link Calendar#JANUARY Calendar.JANUARY},
326     *               {@link Calendar#FEBRUARY Calendar.FEBRUARY}, etc.
327     * @param abbrev One of {@link #LENGTH_LONG}, {@link #LENGTH_MEDIUM},
328     *               or {@link #LENGTH_SHORTEST}.
329     *               Undefined lengths will return {@link #LENGTH_MEDIUM}
330     *               but may return something different in the future.
331     * @return Localized month of the year.
332     */
333    public static String getMonthString(int month, int abbrev) {
334        // Note that here we use sMonthsMedium for MEDIUM, SHORT and SHORTER.
335        // This is a shortcut to not spam the translators with too many variations
336        // of the same string.  If we find that in a language the distinction
337        // is necessary, we can can add more without changing this API.
338        int[] list;
339        switch (abbrev) {
340            case LENGTH_LONG:       list = sMonthsLong;     break;
341            case LENGTH_MEDIUM:     list = sMonthsMedium;   break;
342            case LENGTH_SHORT:      list = sMonthsMedium;   break;
343            case LENGTH_SHORTER:    list = sMonthsMedium;   break;
344            case LENGTH_SHORTEST:   list = sMonthsShortest; break;
345            default:                list = sMonthsMedium;   break;
346        }
347
348        Resources r = Resources.getSystem();
349        return r.getString(list[month - Calendar.JANUARY]);
350    }
351
352    /**
353     * Return a localized string for the month of the year, for
354     * contexts where the month is not formatted together with
355     * a day of the month.
356     *
357     * @param month One of {@link Calendar#JANUARY Calendar.JANUARY},
358     *               {@link Calendar#FEBRUARY Calendar.FEBRUARY}, etc.
359     * @param abbrev One of {@link #LENGTH_LONG}, {@link #LENGTH_MEDIUM},
360     *               or {@link #LENGTH_SHORTEST}.
361     *               Undefined lengths will return {@link #LENGTH_MEDIUM}
362     *               but may return something different in the future.
363     * @return Localized month of the year.
364     * @hide Pending API council approval
365     */
366    public static String getStandaloneMonthString(int month, int abbrev) {
367        // Note that here we use sMonthsMedium for MEDIUM, SHORT and SHORTER.
368        // This is a shortcut to not spam the translators with too many variations
369        // of the same string.  If we find that in a language the distinction
370        // is necessary, we can can add more without changing this API.
371        int[] list;
372        switch (abbrev) {
373            case LENGTH_LONG:       list = sMonthsStandaloneLong;
374                                                            break;
375            case LENGTH_MEDIUM:     list = sMonthsMedium;   break;
376            case LENGTH_SHORT:      list = sMonthsMedium;   break;
377            case LENGTH_SHORTER:    list = sMonthsMedium;   break;
378            case LENGTH_SHORTEST:   list = sMonthsShortest; break;
379            default:                list = sMonthsMedium;   break;
380        }
381
382        Resources r = Resources.getSystem();
383        return r.getString(list[month - Calendar.JANUARY]);
384    }
385
386    /**
387     * Returns a string describing the elapsed time since startTime.
388     * @param startTime some time in the past.
389     * @return a String object containing the elapsed time.
390     * @see #getRelativeTimeSpanString(long, long, long)
391     */
392    public static CharSequence getRelativeTimeSpanString(long startTime) {
393        return getRelativeTimeSpanString(startTime, System.currentTimeMillis(), MINUTE_IN_MILLIS);
394    }
395
396    /**
397     * Returns a string describing 'time' as a time relative to 'now'.
398     * <p>
399     * Time spans in the past are formatted like "42 minutes ago".
400     * Time spans in the future are formatted like "in 42 minutes".
401     *
402     * @param time the time to describe, in milliseconds
403     * @param now the current time in milliseconds
404     * @param minResolution the minimum timespan to report. For example, a time 3 seconds in the
405     *     past will be reported as "0 minutes ago" if this is set to MINUTE_IN_MILLIS. Pass one of
406     *     0, MINUTE_IN_MILLIS, HOUR_IN_MILLIS, DAY_IN_MILLIS, WEEK_IN_MILLIS
407     */
408    public static CharSequence getRelativeTimeSpanString(long time, long now, long minResolution) {
409        int flags = FORMAT_SHOW_DATE | FORMAT_SHOW_YEAR | FORMAT_ABBREV_MONTH;
410        return getRelativeTimeSpanString(time, now, minResolution, flags);
411    }
412
413    /**
414     * Returns a string describing 'time' as a time relative to 'now'.
415     * <p>
416     * Time spans in the past are formatted like "42 minutes ago". Time spans in
417     * the future are formatted like "in 42 minutes".
418     * <p>
419     * Can use {@link #FORMAT_ABBREV_RELATIVE} flag to use abbreviated relative
420     * times, like "42 mins ago".
421     *
422     * @param time the time to describe, in milliseconds
423     * @param now the current time in milliseconds
424     * @param minResolution the minimum timespan to report. For example, a time
425     *            3 seconds in the past will be reported as "0 minutes ago" if
426     *            this is set to MINUTE_IN_MILLIS. Pass one of 0,
427     *            MINUTE_IN_MILLIS, HOUR_IN_MILLIS, DAY_IN_MILLIS,
428     *            WEEK_IN_MILLIS
429     * @param flags a bit mask of formatting options, such as
430     *            {@link #FORMAT_NUMERIC_DATE} or
431     *            {@link #FORMAT_ABBREV_RELATIVE}
432     */
433    public static CharSequence getRelativeTimeSpanString(long time, long now, long minResolution,
434            int flags) {
435        Resources r = Resources.getSystem();
436        boolean abbrevRelative = (flags & (FORMAT_ABBREV_RELATIVE | FORMAT_ABBREV_ALL)) != 0;
437
438        boolean past = (now >= time);
439        long duration = Math.abs(now - time);
440
441        int resId;
442        long count;
443        if (duration < MINUTE_IN_MILLIS && minResolution < MINUTE_IN_MILLIS) {
444            count = duration / SECOND_IN_MILLIS;
445            if (past) {
446                if (abbrevRelative) {
447                    resId = com.android.internal.R.plurals.abbrev_num_seconds_ago;
448                } else {
449                    resId = com.android.internal.R.plurals.num_seconds_ago;
450                }
451            } else {
452                if (abbrevRelative) {
453                    resId = com.android.internal.R.plurals.abbrev_in_num_seconds;
454                } else {
455                    resId = com.android.internal.R.plurals.in_num_seconds;
456                }
457            }
458        } else if (duration < HOUR_IN_MILLIS && minResolution < HOUR_IN_MILLIS) {
459            count = duration / MINUTE_IN_MILLIS;
460            if (past) {
461                if (abbrevRelative) {
462                    resId = com.android.internal.R.plurals.abbrev_num_minutes_ago;
463                } else {
464                    resId = com.android.internal.R.plurals.num_minutes_ago;
465                }
466            } else {
467                if (abbrevRelative) {
468                    resId = com.android.internal.R.plurals.abbrev_in_num_minutes;
469                } else {
470                    resId = com.android.internal.R.plurals.in_num_minutes;
471                }
472            }
473        } else if (duration < DAY_IN_MILLIS && minResolution < DAY_IN_MILLIS) {
474            count = duration / HOUR_IN_MILLIS;
475            if (past) {
476                if (abbrevRelative) {
477                    resId = com.android.internal.R.plurals.abbrev_num_hours_ago;
478                } else {
479                    resId = com.android.internal.R.plurals.num_hours_ago;
480                }
481            } else {
482                if (abbrevRelative) {
483                    resId = com.android.internal.R.plurals.abbrev_in_num_hours;
484                } else {
485                    resId = com.android.internal.R.plurals.in_num_hours;
486                }
487            }
488        } else if (duration < WEEK_IN_MILLIS && minResolution < WEEK_IN_MILLIS) {
489            count = duration / DAY_IN_MILLIS;
490            if (past) {
491                if (abbrevRelative) {
492                    resId = com.android.internal.R.plurals.abbrev_num_days_ago;
493                } else {
494                    resId = com.android.internal.R.plurals.num_days_ago;
495                }
496            } else {
497                if (abbrevRelative) {
498                    resId = com.android.internal.R.plurals.abbrev_in_num_days;
499                } else {
500                    resId = com.android.internal.R.plurals.in_num_days;
501                }
502            }
503        } else {
504            // We know that we won't be showing the time, so it is safe to pass
505            // in a null context.
506            return formatDateRange(null, time, time, flags);
507        }
508
509        String format = r.getQuantityString(resId, (int) count);
510        return String.format(format, count);
511    }
512
513    /**
514     * Return string describing the elapsed time since startTime formatted like
515     * "[relative time/date], [time]".
516     * <p>
517     * Example output strings for the US date format.
518     * <ul>
519     * <li>3 mins ago, 10:15 AM</li>
520     * <li>yesterday, 12:20 PM</li>
521     * <li>Dec 12, 4:12 AM</li>
522     * <li>11/14/2007, 8:20 AM</li>
523     * </ul>
524     *
525     * @param time some time in the past.
526     * @param minResolution the minimum elapsed time (in milliseconds) to report
527     *            when showing relative times. For example, a time 3 seconds in
528     *            the past will be reported as "0 minutes ago" if this is set to
529     *            {@link #MINUTE_IN_MILLIS}.
530     * @param transitionResolution the elapsed time (in milliseconds) at which
531     *            to stop reporting relative measurements. Elapsed times greater
532     *            than this resolution will default to normal date formatting.
533     *            For example, will transition from "6 days ago" to "Dec 12"
534     *            when using {@link #WEEK_IN_MILLIS}.
535     */
536    public static CharSequence getRelativeDateTimeString(Context c, long time, long minResolution,
537            long transitionResolution, int flags) {
538        Resources r = Resources.getSystem();
539
540        long now = System.currentTimeMillis();
541        long duration = Math.abs(now - time);
542
543        // getRelativeTimeSpanString() doesn't correctly format relative dates
544        // above a week or exact dates below a day, so clamp
545        // transitionResolution as needed.
546        if (transitionResolution > WEEK_IN_MILLIS) {
547            transitionResolution = WEEK_IN_MILLIS;
548        } else if (transitionResolution < DAY_IN_MILLIS) {
549            transitionResolution = DAY_IN_MILLIS;
550        }
551
552        CharSequence timeClause = formatDateRange(c, time, time, FORMAT_SHOW_TIME);
553
554        String result;
555        if (duration < transitionResolution) {
556            CharSequence relativeClause = getRelativeTimeSpanString(time, now, minResolution, flags);
557            result = r.getString(com.android.internal.R.string.relative_time, relativeClause, timeClause);
558        } else {
559            CharSequence dateClause = getRelativeTimeSpanString(c, time, false);
560            result = r.getString(com.android.internal.R.string.date_time, dateClause, timeClause);
561        }
562
563        return result;
564    }
565
566    /**
567     * Returns a string describing a day relative to the current day. For example if the day is
568     * today this function returns "Today", if the day was a week ago it returns "7 days ago", and
569     * if the day is in 2 weeks it returns "in 14 days".
570     *
571     * @param r the resources to get the strings from
572     * @param day the relative day to describe in UTC milliseconds
573     * @param today the current time in UTC milliseconds
574     * @return a formatting string
575     */
576    private static final String getRelativeDayString(Resources r, long day, long today) {
577        Time startTime = new Time();
578        startTime.set(day);
579        Time currentTime = new Time();
580        currentTime.set(today);
581
582        int startDay = Time.getJulianDay(day, startTime.gmtoff);
583        int currentDay = Time.getJulianDay(today, currentTime.gmtoff);
584
585        int days = Math.abs(currentDay - startDay);
586        boolean past = (today > day);
587
588        if (days == 1) {
589            if (past) {
590                return r.getString(com.android.internal.R.string.yesterday);
591            } else {
592                return r.getString(com.android.internal.R.string.tomorrow);
593            }
594        } else if (days == 0) {
595            return r.getString(com.android.internal.R.string.today);
596        }
597
598        int resId;
599        if (past) {
600            resId = com.android.internal.R.plurals.num_days_ago;
601        } else {
602            resId = com.android.internal.R.plurals.in_num_days;
603        }
604
605        String format = r.getQuantityString(resId, days);
606        return String.format(format, days);
607    }
608
609    private static void initFormatStrings() {
610        synchronized (sLock) {
611            Resources r = Resources.getSystem();
612            Configuration cfg = r.getConfiguration();
613            if (sLastConfig == null || !sLastConfig.equals(cfg)) {
614                sLastConfig = cfg;
615                sStatusTimeFormat = java.text.DateFormat.getTimeInstance(java.text.DateFormat.SHORT);
616                sElapsedFormatMMSS = r.getString(com.android.internal.R.string.elapsed_time_short_format_mm_ss);
617                sElapsedFormatHMMSS = r.getString(com.android.internal.R.string.elapsed_time_short_format_h_mm_ss);
618            }
619        }
620    }
621
622    /**
623     * Format a time so it appears like it would in the status bar clock.
624     * @deprecated use {@link #DateFormat.getTimeFormat(Context)} instead.
625     * @hide
626     */
627    public static final CharSequence timeString(long millis) {
628        initFormatStrings();
629        return sStatusTimeFormat.format(millis);
630    }
631
632    /**
633     * Formats an elapsed time in the form "MM:SS" or "H:MM:SS"
634     * for display on the call-in-progress screen.
635     * @param elapsedSeconds the elapsed time in seconds.
636     */
637    public static String formatElapsedTime(long elapsedSeconds) {
638        return formatElapsedTime(null, elapsedSeconds);
639    }
640
641    /**
642     * Formats an elapsed time in the form "MM:SS" or "H:MM:SS"
643     * for display on the call-in-progress screen.
644     *
645     * @param recycle {@link StringBuilder} to recycle, if possible
646     * @param elapsedSeconds the elapsed time in seconds.
647     */
648    public static String formatElapsedTime(StringBuilder recycle, long elapsedSeconds) {
649        initFormatStrings();
650
651        long hours = 0;
652        long minutes = 0;
653        long seconds = 0;
654
655        if (elapsedSeconds >= 3600) {
656            hours = elapsedSeconds / 3600;
657            elapsedSeconds -= hours * 3600;
658        }
659        if (elapsedSeconds >= 60) {
660            minutes = elapsedSeconds / 60;
661            elapsedSeconds -= minutes * 60;
662        }
663        seconds = elapsedSeconds;
664
665        String result;
666        if (hours > 0) {
667            return formatElapsedTime(recycle, sElapsedFormatHMMSS, hours, minutes, seconds);
668        } else {
669            return formatElapsedTime(recycle, sElapsedFormatMMSS, minutes, seconds);
670        }
671    }
672
673    /**
674     * Fast formatting of h:mm:ss
675     */
676    private static String formatElapsedTime(StringBuilder recycle, String format, long hours,
677            long minutes, long seconds) {
678        if (FAST_FORMAT_HMMSS.equals(format)) {
679            StringBuilder sb = recycle;
680            if (sb == null) {
681                sb = new StringBuilder(8);
682            } else {
683                sb.setLength(0);
684            }
685            sb.append(hours);
686            sb.append(TIME_SEPARATOR);
687            if (minutes < 10) {
688                sb.append(TIME_PADDING);
689            } else {
690                sb.append(toDigitChar(minutes / 10));
691            }
692            sb.append(toDigitChar(minutes % 10));
693            sb.append(TIME_SEPARATOR);
694            if (seconds < 10) {
695                sb.append(TIME_PADDING);
696            } else {
697                sb.append(toDigitChar(seconds / 10));
698            }
699            sb.append(toDigitChar(seconds % 10));
700            return sb.toString();
701        } else {
702            return String.format(format, hours, minutes, seconds);
703        }
704    }
705
706    /**
707     * Fast formatting of m:ss
708     */
709    private static String formatElapsedTime(StringBuilder recycle, String format, long minutes,
710            long seconds) {
711        if (FAST_FORMAT_MMSS.equals(format)) {
712            StringBuilder sb = recycle;
713            if (sb == null) {
714                sb = new StringBuilder(8);
715            } else {
716                sb.setLength(0);
717            }
718            if (minutes < 10) {
719                sb.append(TIME_PADDING);
720            } else {
721                sb.append(toDigitChar(minutes / 10));
722            }
723            sb.append(toDigitChar(minutes % 10));
724            sb.append(TIME_SEPARATOR);
725            if (seconds < 10) {
726                sb.append(TIME_PADDING);
727            } else {
728                sb.append(toDigitChar(seconds / 10));
729            }
730            sb.append(toDigitChar(seconds % 10));
731            return sb.toString();
732        } else {
733            return String.format(format, minutes, seconds);
734        }
735    }
736
737    private static char toDigitChar(long digit) {
738        return (char) (digit + '0');
739    }
740
741    /**
742     * Format a date / time such that if the then is on the same day as now, it shows
743     * just the time and if it's a different day, it shows just the date.
744     *
745     * <p>The parameters dateFormat and timeFormat should each be one of
746     * {@link java.text.DateFormat#DEFAULT},
747     * {@link java.text.DateFormat#FULL},
748     * {@link java.text.DateFormat#LONG},
749     * {@link java.text.DateFormat#MEDIUM}
750     * or
751     * {@link java.text.DateFormat#SHORT}
752     *
753     * @param then the date to format
754     * @param now the base time
755     * @param dateStyle how to format the date portion.
756     * @param timeStyle how to format the time portion.
757     */
758    public static final CharSequence formatSameDayTime(long then, long now,
759            int dateStyle, int timeStyle) {
760        Calendar thenCal = new GregorianCalendar();
761        thenCal.setTimeInMillis(then);
762        Date thenDate = thenCal.getTime();
763        Calendar nowCal = new GregorianCalendar();
764        nowCal.setTimeInMillis(now);
765
766        java.text.DateFormat f;
767
768        if (thenCal.get(Calendar.YEAR) == nowCal.get(Calendar.YEAR)
769                && thenCal.get(Calendar.MONTH) == nowCal.get(Calendar.MONTH)
770                && thenCal.get(Calendar.DAY_OF_MONTH) == nowCal.get(Calendar.DAY_OF_MONTH)) {
771            f = java.text.DateFormat.getTimeInstance(timeStyle);
772        } else {
773            f = java.text.DateFormat.getDateInstance(dateStyle);
774        }
775        return f.format(thenDate);
776    }
777
778    /**
779     * @hide
780     * @deprecated use {@link android.text.format.Time}
781     */
782    public static Calendar newCalendar(boolean zulu)
783    {
784        if (zulu)
785            return Calendar.getInstance(TimeZone.getTimeZone("GMT"));
786
787        return Calendar.getInstance();
788    }
789
790    /**
791     * @return true if the supplied when is today else false
792     */
793    public static boolean isToday(long when) {
794        Time time = new Time();
795        time.set(when);
796
797        int thenYear = time.year;
798        int thenMonth = time.month;
799        int thenMonthDay = time.monthDay;
800
801        time.set(System.currentTimeMillis());
802        return (thenYear == time.year)
803                && (thenMonth == time.month)
804                && (thenMonthDay == time.monthDay);
805    }
806
807    /**
808     * @hide
809     * @deprecated use {@link android.text.format.Time}
810     */
811    private static final int ctoi(String str, int index)
812                                                throws DateException
813    {
814        char c = str.charAt(index);
815        if (c >= '0' && c <= '9') {
816            return (int)(c - '0');
817        }
818        throw new DateException("Expected numeric character.  Got '" +
819                                            c + "'");
820    }
821
822    /**
823     * @hide
824     * @deprecated use {@link android.text.format.Time}
825     */
826    private static final int check(int lowerBound, int upperBound, int value)
827                                                throws DateException
828    {
829        if (value >= lowerBound && value <= upperBound) {
830            return value;
831        }
832        throw new DateException("field out of bounds.  max=" + upperBound
833                                        + " value=" + value);
834    }
835
836    /**
837     * @hide
838     * @deprecated use {@link android.text.format.Time}
839     * Return true if this date string is local time
840     */
841    public static boolean isUTC(String s)
842    {
843        if (s.length() == 16 && s.charAt(15) == 'Z') {
844            return true;
845        }
846        if (s.length() == 9 && s.charAt(8) == 'Z') {
847            // XXX not sure if this case possible/valid
848            return true;
849        }
850        return false;
851    }
852
853
854    // note that month in Calendar is 0 based and in all other human
855    // representations, it's 1 based.
856    // Returns if the Z was present, meaning that the time is in UTC
857    /**
858     * @hide
859     * @deprecated use {@link android.text.format.Time}
860     */
861    public static boolean parseDateTime(String str, Calendar cal)
862                                                throws DateException
863    {
864        int len = str.length();
865        boolean dateTime = (len == 15 || len == 16) && str.charAt(8) == 'T';
866        boolean justDate = len == 8;
867        if (dateTime || justDate) {
868            cal.clear();
869            cal.set(Calendar.YEAR,
870                            ctoi(str, 0)*1000 + ctoi(str, 1)*100
871                            + ctoi(str, 2)*10 + ctoi(str, 3));
872            cal.set(Calendar.MONTH,
873                            check(0, 11, ctoi(str, 4)*10 + ctoi(str, 5) - 1));
874            cal.set(Calendar.DAY_OF_MONTH,
875                            check(1, 31, ctoi(str, 6)*10 + ctoi(str, 7)));
876            if (dateTime) {
877                cal.set(Calendar.HOUR_OF_DAY,
878                            check(0, 23, ctoi(str, 9)*10 + ctoi(str, 10)));
879                cal.set(Calendar.MINUTE,
880                            check(0, 59, ctoi(str, 11)*10 + ctoi(str, 12)));
881                cal.set(Calendar.SECOND,
882                            check(0, 59, ctoi(str, 13)*10 + ctoi(str, 14)));
883            }
884            if (justDate) {
885                cal.set(Calendar.HOUR_OF_DAY, 0);
886                cal.set(Calendar.MINUTE, 0);
887                cal.set(Calendar.SECOND, 0);
888                return true;
889            }
890            if (len == 15) {
891                return false;
892            }
893            if (str.charAt(15) == 'Z') {
894                return true;
895            }
896        }
897        throw new DateException("Invalid time (expected "
898                                + "YYYYMMDDThhmmssZ? got '" + str + "').");
899    }
900
901    /**
902     * Given a timezone string which can be null, and a dateTime string,
903     * set that time into a calendar.
904     * @hide
905     * @deprecated use {@link android.text.format.Time}
906     */
907    public static void parseDateTime(String tz, String dateTime, Calendar out)
908                                                throws DateException
909    {
910        TimeZone timezone;
911        if (DateUtils.isUTC(dateTime)) {
912            timezone = TimeZone.getTimeZone("UTC");
913        }
914        else if (tz == null) {
915            timezone = TimeZone.getDefault();
916        }
917        else {
918            timezone = TimeZone.getTimeZone(tz);
919        }
920
921        Calendar local = new GregorianCalendar(timezone);
922        DateUtils.parseDateTime(dateTime, local);
923
924        out.setTimeInMillis(local.getTimeInMillis());
925    }
926
927
928    /**
929     * Return a string containing the date and time in RFC2445 format.
930     * Ensures that the time is written in UTC.  The Calendar class doesn't
931     * really help out with this, so this is slower than it ought to be.
932     *
933     * @param cal the date and time to write
934     * @hide
935     * @deprecated use {@link android.text.format.Time}
936     */
937    public static String writeDateTime(Calendar cal)
938    {
939        TimeZone tz = TimeZone.getTimeZone("GMT");
940        GregorianCalendar c = new GregorianCalendar(tz);
941        c.setTimeInMillis(cal.getTimeInMillis());
942        return writeDateTime(c, true);
943    }
944
945    /**
946     * Return a string containing the date and time in RFC2445 format.
947     *
948     * @param cal the date and time to write
949     * @param zulu If the calendar is in UTC, pass true, and a Z will
950     * be written at the end as per RFC2445.  Otherwise, the time is
951     * considered in localtime.
952     * @hide
953     * @deprecated use {@link android.text.format.Time}
954     */
955    public static String writeDateTime(Calendar cal, boolean zulu)
956    {
957        StringBuilder sb = new StringBuilder();
958        sb.ensureCapacity(16);
959        if (zulu) {
960            sb.setLength(16);
961            sb.setCharAt(15, 'Z');
962        } else {
963            sb.setLength(15);
964        }
965        return writeDateTime(cal, sb);
966    }
967
968    /**
969     * Return a string containing the date and time in RFC2445 format.
970     *
971     * @param cal the date and time to write
972     * @param sb a StringBuilder to use.  It is assumed that setLength
973     *           has already been called on sb to the appropriate length
974     *           which is sb.setLength(zulu ? 16 : 15)
975     * @hide
976     * @deprecated use {@link android.text.format.Time}
977     */
978    public static String writeDateTime(Calendar cal, StringBuilder sb)
979    {
980        int n;
981
982        n = cal.get(Calendar.YEAR);
983        sb.setCharAt(3, (char)('0'+n%10));
984        n /= 10;
985        sb.setCharAt(2, (char)('0'+n%10));
986        n /= 10;
987        sb.setCharAt(1, (char)('0'+n%10));
988        n /= 10;
989        sb.setCharAt(0, (char)('0'+n%10));
990
991        n = cal.get(Calendar.MONTH) + 1;
992        sb.setCharAt(5, (char)('0'+n%10));
993        n /= 10;
994        sb.setCharAt(4, (char)('0'+n%10));
995
996        n = cal.get(Calendar.DAY_OF_MONTH);
997        sb.setCharAt(7, (char)('0'+n%10));
998        n /= 10;
999        sb.setCharAt(6, (char)('0'+n%10));
1000
1001        sb.setCharAt(8, 'T');
1002
1003        n = cal.get(Calendar.HOUR_OF_DAY);
1004        sb.setCharAt(10, (char)('0'+n%10));
1005        n /= 10;
1006        sb.setCharAt(9, (char)('0'+n%10));
1007
1008        n = cal.get(Calendar.MINUTE);
1009        sb.setCharAt(12, (char)('0'+n%10));
1010        n /= 10;
1011        sb.setCharAt(11, (char)('0'+n%10));
1012
1013        n = cal.get(Calendar.SECOND);
1014        sb.setCharAt(14, (char)('0'+n%10));
1015        n /= 10;
1016        sb.setCharAt(13, (char)('0'+n%10));
1017
1018        return sb.toString();
1019    }
1020
1021    /**
1022     * @hide
1023     * @deprecated use {@link android.text.format.Time}
1024     */
1025    public static void assign(Calendar lval, Calendar rval)
1026    {
1027        // there should be a faster way.
1028        lval.clear();
1029        lval.setTimeInMillis(rval.getTimeInMillis());
1030    }
1031
1032    /**
1033     * Formats a date or a time range according to the local conventions.
1034     *
1035     * <p>
1036     * Example output strings (date formats in these examples are shown using
1037     * the US date format convention but that may change depending on the
1038     * local settings):
1039     * <ul>
1040     *   <li>10:15am</li>
1041     *   <li>3:00pm - 4:00pm</li>
1042     *   <li>3pm - 4pm</li>
1043     *   <li>3PM - 4PM</li>
1044     *   <li>08:00 - 17:00</li>
1045     *   <li>Oct 9</li>
1046     *   <li>Tue, Oct 9</li>
1047     *   <li>October 9, 2007</li>
1048     *   <li>Oct 9 - 10</li>
1049     *   <li>Oct 9 - 10, 2007</li>
1050     *   <li>Oct 28 - Nov 3, 2007</li>
1051     *   <li>Dec 31, 2007 - Jan 1, 2008</li>
1052     *   <li>Oct 9, 8:00am - Oct 10, 5:00pm</li>
1053     *   <li>12/31/2007 - 01/01/2008</li>
1054     * </ul>
1055     *
1056     * <p>
1057     * The flags argument is a bitmask of options from the following list:
1058     *
1059     * <ul>
1060     *   <li>FORMAT_SHOW_TIME</li>
1061     *   <li>FORMAT_SHOW_WEEKDAY</li>
1062     *   <li>FORMAT_SHOW_YEAR</li>
1063     *   <li>FORMAT_NO_YEAR</li>
1064     *   <li>FORMAT_SHOW_DATE</li>
1065     *   <li>FORMAT_NO_MONTH_DAY</li>
1066     *   <li>FORMAT_12HOUR</li>
1067     *   <li>FORMAT_24HOUR</li>
1068     *   <li>FORMAT_CAP_AMPM</li>
1069     *   <li>FORMAT_NO_NOON</li>
1070     *   <li>FORMAT_CAP_NOON</li>
1071     *   <li>FORMAT_NO_MIDNIGHT</li>
1072     *   <li>FORMAT_CAP_MIDNIGHT</li>
1073     *   <li>FORMAT_UTC</li>
1074     *   <li>FORMAT_ABBREV_TIME</li>
1075     *   <li>FORMAT_ABBREV_WEEKDAY</li>
1076     *   <li>FORMAT_ABBREV_MONTH</li>
1077     *   <li>FORMAT_ABBREV_ALL</li>
1078     *   <li>FORMAT_NUMERIC_DATE</li>
1079     * </ul>
1080     *
1081     * <p>
1082     * If FORMAT_SHOW_TIME is set, the time is shown as part of the date range.
1083     * If the start and end time are the same, then just the start time is
1084     * shown.
1085     *
1086     * <p>
1087     * If FORMAT_SHOW_WEEKDAY is set, then the weekday is shown.
1088     *
1089     * <p>
1090     * If FORMAT_SHOW_YEAR is set, then the year is always shown.
1091     * If FORMAT_NO_YEAR is set, then the year is not shown.
1092     * If neither FORMAT_SHOW_YEAR nor FORMAT_NO_YEAR are set, then the year
1093     * is shown only if it is different from the current year, or if the start
1094     * and end dates fall on different years.  If both are set,
1095     * FORMAT_SHOW_YEAR takes precedence.
1096     *
1097     * <p>
1098     * Normally the date is shown unless the start and end day are the same.
1099     * If FORMAT_SHOW_DATE is set, then the date is always shown, even for
1100     * same day ranges.
1101     *
1102     * <p>
1103     * If FORMAT_NO_MONTH_DAY is set, then if the date is shown, just the
1104     * month name will be shown, not the day of the month.  For example,
1105     * "January, 2008" instead of "January 6 - 12, 2008".
1106     *
1107     * <p>
1108     * If FORMAT_CAP_AMPM is set and 12-hour time is used, then the "AM"
1109     * and "PM" are capitalized.
1110     *
1111     * <p>
1112     * If FORMAT_NO_NOON is set and 12-hour time is used, then "12pm" is
1113     * shown instead of "noon".
1114     *
1115     * <p>
1116     * If FORMAT_CAP_NOON is set and 12-hour time is used, then "Noon" is
1117     * shown instead of "noon".
1118     *
1119     * <p>
1120     * If FORMAT_NO_MIDNIGHT is set and 12-hour time is used, then "12am" is
1121     * shown instead of "midnight".
1122     *
1123     * <p>
1124     * If FORMAT_CAP_NOON is set and 12-hour time is used, then "Midnight" is
1125     * shown instead of "midnight".
1126     *
1127     * <p>
1128     * If FORMAT_12HOUR is set and the time is shown, then the time is
1129     * shown in the 12-hour time format. You should not normally set this.
1130     * Instead, let the time format be chosen automatically according to the
1131     * system settings. If both FORMAT_12HOUR and FORMAT_24HOUR are set, then
1132     * FORMAT_24HOUR takes precedence.
1133     *
1134     * <p>
1135     * If FORMAT_24HOUR is set and the time is shown, then the time is
1136     * shown in the 24-hour time format. You should not normally set this.
1137     * Instead, let the time format be chosen automatically according to the
1138     * system settings. If both FORMAT_12HOUR and FORMAT_24HOUR are set, then
1139     * FORMAT_24HOUR takes precedence.
1140     *
1141     * <p>
1142     * If FORMAT_UTC is set, then the UTC timezone is used for the start
1143     * and end milliseconds.
1144     *
1145     * <p>
1146     * If FORMAT_ABBREV_TIME is set and 12-hour time format is used, then the
1147     * start and end times (if shown) are abbreviated by not showing the minutes
1148     * if they are zero.  For example, instead of "3:00pm" the time would be
1149     * abbreviated to "3pm".
1150     *
1151     * <p>
1152     * If FORMAT_ABBREV_WEEKDAY is set, then the weekday (if shown) is
1153     * abbreviated to a 3-letter string.
1154     *
1155     * <p>
1156     * If FORMAT_ABBREV_MONTH is set, then the month (if shown) is abbreviated
1157     * to a 3-letter string.
1158     *
1159     * <p>
1160     * If FORMAT_ABBREV_ALL is set, then the weekday and the month (if shown)
1161     * are abbreviated to 3-letter strings.
1162     *
1163     * <p>
1164     * If FORMAT_NUMERIC_DATE is set, then the date is shown in numeric format
1165     * instead of using the name of the month.  For example, "12/31/2008"
1166     * instead of "December 31, 2008".
1167     *
1168     * @param context the context is required only if the time is shown
1169     * @param startMillis the start time in UTC milliseconds
1170     * @param endMillis the end time in UTC milliseconds
1171     * @param flags a bit mask of options
1172     *
1173     * @return a string containing the formatted date/time range.
1174     */
1175    public static String formatDateRange(Context context, long startMillis,
1176                long endMillis, int flags) {
1177        Resources res = Resources.getSystem();
1178        boolean showTime = (flags & FORMAT_SHOW_TIME) != 0;
1179        boolean showWeekDay = (flags & FORMAT_SHOW_WEEKDAY) != 0;
1180        boolean showYear = (flags & FORMAT_SHOW_YEAR) != 0;
1181        boolean noYear = (flags & FORMAT_NO_YEAR) != 0;
1182        boolean useUTC = (flags & FORMAT_UTC) != 0;
1183        boolean abbrevWeekDay = (flags & (FORMAT_ABBREV_WEEKDAY | FORMAT_ABBREV_ALL)) != 0;
1184        boolean abbrevMonth = (flags & (FORMAT_ABBREV_MONTH | FORMAT_ABBREV_ALL)) != 0;
1185        boolean noMonthDay = (flags & FORMAT_NO_MONTH_DAY) != 0;
1186        boolean numericDate = (flags & FORMAT_NUMERIC_DATE) != 0;
1187
1188        // If we're getting called with a single instant in time (from
1189        // e.g. formatDateTime(), below), then we can skip a lot of
1190        // computation below that'd otherwise be thrown out.
1191        boolean isInstant = (startMillis == endMillis);
1192
1193        Time startDate = useUTC ? new Time(Time.TIMEZONE_UTC) : new Time();
1194        startDate.set(startMillis);
1195
1196        Time endDate;
1197        int dayDistance;
1198        if (isInstant) {
1199            endDate = startDate;
1200            dayDistance = 0;
1201        } else {
1202            endDate = useUTC ? new Time(Time.TIMEZONE_UTC) : new Time();
1203            endDate.set(endMillis);
1204            int startJulianDay = Time.getJulianDay(startMillis, startDate.gmtoff);
1205            int endJulianDay = Time.getJulianDay(endMillis, endDate.gmtoff);
1206            dayDistance = endJulianDay - startJulianDay;
1207        }
1208
1209        // If the end date ends at 12am at the beginning of a day,
1210        // then modify it to make it look like it ends at midnight on
1211        // the previous day.  This will allow us to display "8pm - midnight",
1212        // for example, instead of "Nov 10, 8pm - Nov 11, 12am". But we only do
1213        // this if it is midnight of the same day as the start date because
1214        // for multiple-day events, an end time of "midnight on Nov 11" is
1215        // ambiguous and confusing (is that midnight the start of Nov 11, or
1216        // the end of Nov 11?).
1217        // If we are not showing the time then also adjust the end date
1218        // for multiple-day events.  This is to allow us to display, for
1219        // example, "Nov 10 -11" for an event with a start date of Nov 10
1220        // and an end date of Nov 12 at 00:00.
1221        // If the start and end time are the same, then skip this and don't
1222        // adjust the date.
1223        if (!isInstant
1224            && (endDate.hour | endDate.minute | endDate.second) == 0
1225            && (!showTime || dayDistance <= 1)) {
1226            endDate.monthDay -= 1;
1227            endDate.normalize(true /* ignore isDst */);
1228        }
1229
1230        int startDay = startDate.monthDay;
1231        int startMonthNum = startDate.month;
1232        int startYear = startDate.year;
1233
1234        int endDay = endDate.monthDay;
1235        int endMonthNum = endDate.month;
1236        int endYear = endDate.year;
1237
1238        String startWeekDayString = "";
1239        String endWeekDayString = "";
1240        if (showWeekDay) {
1241            String weekDayFormat = "";
1242            if (abbrevWeekDay) {
1243                weekDayFormat = ABBREV_WEEKDAY_FORMAT;
1244            } else {
1245                weekDayFormat = WEEKDAY_FORMAT;
1246            }
1247            startWeekDayString = startDate.format(weekDayFormat);
1248            endWeekDayString = isInstant ? startWeekDayString : endDate.format(weekDayFormat);
1249        }
1250
1251        String startTimeString = "";
1252        String endTimeString = "";
1253        if (showTime) {
1254            String startTimeFormat = "";
1255            String endTimeFormat = "";
1256            boolean force24Hour = (flags & FORMAT_24HOUR) != 0;
1257            boolean force12Hour = (flags & FORMAT_12HOUR) != 0;
1258            boolean use24Hour;
1259            if (force24Hour) {
1260                use24Hour = true;
1261            } else if (force12Hour) {
1262                use24Hour = false;
1263            } else {
1264                use24Hour = DateFormat.is24HourFormat(context);
1265            }
1266            if (use24Hour) {
1267                startTimeFormat = HOUR_MINUTE_24;
1268                endTimeFormat = HOUR_MINUTE_24;
1269            } else {
1270                boolean abbrevTime = (flags & (FORMAT_ABBREV_TIME | FORMAT_ABBREV_ALL)) != 0;
1271                boolean capAMPM = (flags & FORMAT_CAP_AMPM) != 0;
1272                boolean noNoon = (flags & FORMAT_NO_NOON) != 0;
1273                boolean capNoon = (flags & FORMAT_CAP_NOON) != 0;
1274                boolean noMidnight = (flags & FORMAT_NO_MIDNIGHT) != 0;
1275                boolean capMidnight = (flags & FORMAT_CAP_MIDNIGHT) != 0;
1276
1277                boolean startOnTheHour = startDate.minute == 0 && startDate.second == 0;
1278                boolean endOnTheHour = endDate.minute == 0 && endDate.second == 0;
1279                if (abbrevTime && startOnTheHour) {
1280                    if (capAMPM) {
1281                        startTimeFormat = res.getString(com.android.internal.R.string.hour_cap_ampm);
1282                    } else {
1283                        startTimeFormat = res.getString(com.android.internal.R.string.hour_ampm);
1284                    }
1285                } else {
1286                    if (capAMPM) {
1287                        startTimeFormat = res.getString(com.android.internal.R.string.hour_minute_cap_ampm);
1288                    } else {
1289                        startTimeFormat = res.getString(com.android.internal.R.string.hour_minute_ampm);
1290                    }
1291                }
1292
1293                // Don't waste time on setting endTimeFormat when
1294                // we're dealing with an instant, where we'll never
1295                // need the end point.  (It's the same as the start
1296                // point)
1297                if (!isInstant) {
1298                    if (abbrevTime && endOnTheHour) {
1299                        if (capAMPM) {
1300                            endTimeFormat = res.getString(com.android.internal.R.string.hour_cap_ampm);
1301                        } else {
1302                            endTimeFormat = res.getString(com.android.internal.R.string.hour_ampm);
1303                        }
1304                    } else {
1305                        if (capAMPM) {
1306                            endTimeFormat = res.getString(com.android.internal.R.string.hour_minute_cap_ampm);
1307                        } else {
1308                            endTimeFormat = res.getString(com.android.internal.R.string.hour_minute_ampm);
1309                        }
1310                    }
1311
1312                    if (endDate.hour == 12 && endOnTheHour && !noNoon) {
1313                        if (capNoon) {
1314                            endTimeFormat = res.getString(com.android.internal.R.string.Noon);
1315                        } else {
1316                            endTimeFormat = res.getString(com.android.internal.R.string.noon);
1317                        }
1318                    } else if (endDate.hour == 0 && endOnTheHour && !noMidnight) {
1319                        if (capMidnight) {
1320                            endTimeFormat = res.getString(com.android.internal.R.string.Midnight);
1321                        } else {
1322                            endTimeFormat = res.getString(com.android.internal.R.string.midnight);
1323                        }
1324                    }
1325                }
1326
1327                if (startDate.hour == 12 && startOnTheHour && !noNoon) {
1328                    if (capNoon) {
1329                        startTimeFormat = res.getString(com.android.internal.R.string.Noon);
1330                    } else {
1331                        startTimeFormat = res.getString(com.android.internal.R.string.noon);
1332                    }
1333                    // Don't show the start time starting at midnight.  Show
1334                    // 12am instead.
1335                }
1336            }
1337
1338            startTimeString = startDate.format(startTimeFormat);
1339            endTimeString = isInstant ? startTimeString : endDate.format(endTimeFormat);
1340        }
1341
1342        // Show the year if the user specified FORMAT_SHOW_YEAR or if
1343        // the starting and end years are different from each other
1344        // or from the current year.  But don't show the year if the
1345        // user specified FORMAT_NO_YEAR.
1346        if (showYear) {
1347            // No code... just a comment for clarity.  Keep showYear
1348            // on, as they enabled it with FORMAT_SHOW_YEAR.  This
1349            // takes precedence over them setting FORMAT_NO_YEAR.
1350        } else if (noYear) {
1351            // They explicitly didn't want a year.
1352            showYear = false;
1353        } else if (startYear != endYear) {
1354            showYear = true;
1355        } else {
1356            // Show the year if it's not equal to the current year.
1357            Time currentTime = new Time();
1358            currentTime.setToNow();
1359            showYear = startYear != currentTime.year;
1360        }
1361
1362        String defaultDateFormat, fullFormat, dateRange;
1363        if (numericDate) {
1364            defaultDateFormat = res.getString(com.android.internal.R.string.numeric_date);
1365        } else if (showYear) {
1366            if (abbrevMonth) {
1367                if (noMonthDay) {
1368                    defaultDateFormat = res.getString(com.android.internal.R.string.abbrev_month_year);
1369                } else {
1370                    defaultDateFormat = res.getString(com.android.internal.R.string.abbrev_month_day_year);
1371                }
1372            } else {
1373                if (noMonthDay) {
1374                    defaultDateFormat = res.getString(com.android.internal.R.string.month_year);
1375                } else {
1376                    defaultDateFormat = res.getString(com.android.internal.R.string.month_day_year);
1377                }
1378            }
1379        } else {
1380            if (abbrevMonth) {
1381                if (noMonthDay) {
1382                    defaultDateFormat = res.getString(com.android.internal.R.string.abbrev_month);
1383                } else {
1384                    defaultDateFormat = res.getString(com.android.internal.R.string.abbrev_month_day);
1385                }
1386            } else {
1387                if (noMonthDay) {
1388                    defaultDateFormat = res.getString(com.android.internal.R.string.month);
1389                } else {
1390                    defaultDateFormat = res.getString(com.android.internal.R.string.month_day);
1391                }
1392            }
1393        }
1394
1395        if (showWeekDay) {
1396            if (showTime) {
1397                fullFormat = res.getString(com.android.internal.R.string.wday1_date1_time1_wday2_date2_time2);
1398            } else {
1399                fullFormat = res.getString(com.android.internal.R.string.wday1_date1_wday2_date2);
1400            }
1401        } else {
1402            if (showTime) {
1403                fullFormat = res.getString(com.android.internal.R.string.date1_time1_date2_time2);
1404            } else {
1405                fullFormat = res.getString(com.android.internal.R.string.date1_date2);
1406            }
1407        }
1408
1409        if (noMonthDay && startMonthNum == endMonthNum) {
1410            // Example: "January, 2008"
1411            String startDateString = startDate.format(defaultDateFormat);
1412            return startDateString;
1413        }
1414
1415        if (startYear != endYear || noMonthDay) {
1416            // Different year or we are not showing the month day number.
1417            // Example: "December 31, 2007 - January 1, 2008"
1418            // Or: "January - February, 2008"
1419            String startDateString = startDate.format(defaultDateFormat);
1420            String endDateString = endDate.format(defaultDateFormat);
1421
1422            // The values that are used in a fullFormat string are specified
1423            // by position.
1424            dateRange = String.format(fullFormat,
1425                    startWeekDayString, startDateString, startTimeString,
1426                    endWeekDayString, endDateString, endTimeString);
1427            return dateRange;
1428        }
1429
1430        // Get the month, day, and year strings for the start and end dates
1431        String monthFormat;
1432        if (numericDate) {
1433            monthFormat = NUMERIC_MONTH_FORMAT;
1434        } else if (abbrevMonth) {
1435            monthFormat = ABBREV_MONTH_FORMAT;
1436        } else {
1437            monthFormat = MONTH_FORMAT;
1438        }
1439        String startMonthString = startDate.format(monthFormat);
1440        String startMonthDayString = startDate.format(MONTH_DAY_FORMAT);
1441        String startYearString = startDate.format(YEAR_FORMAT);
1442
1443        String endMonthString = isInstant ? null : endDate.format(monthFormat);
1444        String endMonthDayString = isInstant ? null : endDate.format(MONTH_DAY_FORMAT);
1445        String endYearString = isInstant ? null : endDate.format(YEAR_FORMAT);
1446
1447        if (startMonthNum != endMonthNum) {
1448            // Same year, different month.
1449            // Example: "October 28 - November 3"
1450            // or: "Wed, Oct 31 - Sat, Nov 3, 2007"
1451            // or: "Oct 31, 8am - Sat, Nov 3, 2007, 5pm"
1452
1453            int index = 0;
1454            if (showWeekDay) index = 1;
1455            if (showYear) index += 2;
1456            if (showTime) index += 4;
1457            if (numericDate) index += 8;
1458            int resId = sameYearTable[index];
1459            fullFormat = res.getString(resId);
1460
1461            // The values that are used in a fullFormat string are specified
1462            // by position.
1463            dateRange = String.format(fullFormat,
1464                    startWeekDayString, startMonthString, startMonthDayString,
1465                    startYearString, startTimeString,
1466                    endWeekDayString, endMonthString, endMonthDayString,
1467                    endYearString, endTimeString);
1468            return dateRange;
1469        }
1470
1471        if (startDay != endDay) {
1472            // Same month, different day.
1473            int index = 0;
1474            if (showWeekDay) index = 1;
1475            if (showYear) index += 2;
1476            if (showTime) index += 4;
1477            if (numericDate) index += 8;
1478            int resId = sameMonthTable[index];
1479            fullFormat = res.getString(resId);
1480
1481            // The values that are used in a fullFormat string are specified
1482            // by position.
1483            dateRange = String.format(fullFormat,
1484                    startWeekDayString, startMonthString, startMonthDayString,
1485                    startYearString, startTimeString,
1486                    endWeekDayString, endMonthString, endMonthDayString,
1487                    endYearString, endTimeString);
1488            return dateRange;
1489        }
1490
1491        // Same start and end day
1492        boolean showDate = (flags & FORMAT_SHOW_DATE) != 0;
1493
1494        // If nothing was specified, then show the date.
1495        if (!showTime && !showDate && !showWeekDay) showDate = true;
1496
1497        // Compute the time string (example: "10:00 - 11:00 am")
1498        String timeString = "";
1499        if (showTime) {
1500            // If the start and end time are the same, then just show the
1501            // start time.
1502            if (isInstant) {
1503                // Same start and end time.
1504                // Example: "10:15 AM"
1505                timeString = startTimeString;
1506            } else {
1507                // Example: "10:00 - 11:00 am"
1508                String timeFormat = res.getString(com.android.internal.R.string.time1_time2);
1509                timeString = String.format(timeFormat, startTimeString, endTimeString);
1510            }
1511        }
1512
1513        // Figure out which full format to use.
1514        fullFormat = "";
1515        String dateString = "";
1516        if (showDate) {
1517            dateString = startDate.format(defaultDateFormat);
1518            if (showWeekDay) {
1519                if (showTime) {
1520                    // Example: "10:00 - 11:00 am, Tue, Oct 9"
1521                    fullFormat = res.getString(com.android.internal.R.string.time_wday_date);
1522                } else {
1523                    // Example: "Tue, Oct 9"
1524                    fullFormat = res.getString(com.android.internal.R.string.wday_date);
1525                }
1526            } else {
1527                if (showTime) {
1528                    // Example: "10:00 - 11:00 am, Oct 9"
1529                    fullFormat = res.getString(com.android.internal.R.string.time_date);
1530                } else {
1531                    // Example: "Oct 9"
1532                    return dateString;
1533                }
1534            }
1535        } else if (showWeekDay) {
1536            if (showTime) {
1537                // Example: "10:00 - 11:00 am, Tue"
1538                fullFormat = res.getString(com.android.internal.R.string.time_wday);
1539            } else {
1540                // Example: "Tue"
1541                return startWeekDayString;
1542            }
1543        } else if (showTime) {
1544            return timeString;
1545        }
1546
1547        // The values that are used in a fullFormat string are specified
1548        // by position.
1549        dateRange = String.format(fullFormat, timeString, startWeekDayString, dateString);
1550        return dateRange;
1551    }
1552
1553    /**
1554     * Formats a date or a time according to the local conventions. There are
1555     * lots of options that allow the caller to control, for example, if the
1556     * time is shown, if the day of the week is shown, if the month name is
1557     * abbreviated, if noon is shown instead of 12pm, and so on. For the
1558     * complete list of options, see the documentation for
1559     * {@link #formatDateRange}.
1560     * <p>
1561     * Example output strings (date formats in these examples are shown using
1562     * the US date format convention but that may change depending on the
1563     * local settings):
1564     * <ul>
1565     *   <li>10:15am</li>
1566     *   <li>3:00pm</li>
1567     *   <li>3pm</li>
1568     *   <li>3PM</li>
1569     *   <li>08:00</li>
1570     *   <li>17:00</li>
1571     *   <li>noon</li>
1572     *   <li>Noon</li>
1573     *   <li>midnight</li>
1574     *   <li>Midnight</li>
1575     *   <li>Oct 31</li>
1576     *   <li>Oct 31, 2007</li>
1577     *   <li>October 31, 2007</li>
1578     *   <li>10am, Oct 31</li>
1579     *   <li>17:00, Oct 31</li>
1580     *   <li>Wed</li>
1581     *   <li>Wednesday</li>
1582     *   <li>10am, Wed, Oct 31</li>
1583     *   <li>Wed, Oct 31</li>
1584     *   <li>Wednesday, Oct 31</li>
1585     *   <li>Wed, Oct 31, 2007</li>
1586     *   <li>Wed, October 31</li>
1587     *   <li>10/31/2007</li>
1588     * </ul>
1589     *
1590     * @param context the context is required only if the time is shown
1591     * @param millis a point in time in UTC milliseconds
1592     * @param flags a bit mask of formatting options
1593     * @return a string containing the formatted date/time.
1594     */
1595    public static String formatDateTime(Context context, long millis, int flags) {
1596        return formatDateRange(context, millis, millis, flags);
1597    }
1598
1599    /**
1600     * @return a relative time string to display the time expressed by millis.  Times
1601     * are counted starting at midnight, which means that assuming that the current
1602     * time is March 31st, 0:30:
1603     * <ul>
1604     *   <li>"millis=0:10 today" will be displayed as "0:10"</li>
1605     *   <li>"millis=11:30pm the day before" will be displayed as "Mar 30"</li>
1606     * </ul>
1607     * If the given millis is in a different year, then the full date is
1608     * returned in numeric format (e.g., "10/12/2008").
1609     *
1610     * @param withPreposition If true, the string returned will include the correct
1611     * preposition ("at 9:20am", "on 10/12/2008" or "on May 29").
1612     */
1613    public static CharSequence getRelativeTimeSpanString(Context c, long millis,
1614            boolean withPreposition) {
1615
1616        long now = System.currentTimeMillis();
1617        long span = now - millis;
1618
1619        if (sNowTime == null) {
1620            sNowTime = new Time();
1621            sThenTime = new Time();
1622        }
1623
1624        sNowTime.set(now);
1625        sThenTime.set(millis);
1626
1627        String result;
1628        int prepositionId;
1629        if (span < DAY_IN_MILLIS && sNowTime.weekDay == sThenTime.weekDay) {
1630            // Same day
1631            int flags = FORMAT_SHOW_TIME;
1632            result = formatDateRange(c, millis, millis, flags);
1633            prepositionId = R.string.preposition_for_time;
1634        } else if (sNowTime.year != sThenTime.year) {
1635            // Different years
1636            int flags = FORMAT_SHOW_DATE | FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE;
1637            result = formatDateRange(c, millis, millis, flags);
1638
1639            // This is a date (like "10/31/2008" so use the date preposition)
1640            prepositionId = R.string.preposition_for_date;
1641        } else {
1642            // Default
1643            int flags = FORMAT_SHOW_DATE | FORMAT_ABBREV_MONTH;
1644            result = formatDateRange(c, millis, millis, flags);
1645            prepositionId = R.string.preposition_for_date;
1646        }
1647        if (withPreposition) {
1648            Resources res = c.getResources();
1649            result = res.getString(prepositionId, result);
1650        }
1651        return result;
1652    }
1653
1654    /**
1655     * Convenience function to return relative time string without preposition.
1656     * @param c context for resources
1657     * @param millis time in milliseconds
1658     * @return {@link CharSequence} containing relative time.
1659     * @see #getRelativeTimeSpanString(Context, long, boolean)
1660     */
1661    public static CharSequence getRelativeTimeSpanString(Context c, long millis) {
1662        return getRelativeTimeSpanString(c, millis, false /* no preposition */);
1663    }
1664
1665    private static Time sNowTime;
1666    private static Time sThenTime;
1667}
1668