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