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