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