• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
17 package android.text.format;
18 
19 import com.android.internal.R;
20 
21 import android.content.Context;
22 import android.content.res.Configuration;
23 import android.content.res.Resources;
24 
25 import java.util.Calendar;
26 import java.util.Date;
27 import java.util.Formatter;
28 import java.util.GregorianCalendar;
29 import java.util.Locale;
30 import 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  */
36 public 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      */
getDayOfWeekString(int dayOfWeek, int abbrev)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      */
getAMPMString(int ampm)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      */
getMonthString(int month, int abbrev)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      */
getStandaloneMonthString(int month, int abbrev)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      */
getRelativeTimeSpanString(long startTime)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      */
getRelativeTimeSpanString(long time, long now, long minResolution)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      */
getRelativeTimeSpanString(long time, long now, long minResolution, int flags)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      */
getNumberOfDaysPassed(long date1, long date2)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      */
getRelativeDateTimeString(Context c, long time, long minResolution, long transitionResolution, int flags)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      */
getRelativeDayString(Resources r, long day, long today)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 
initFormatStrings()643     private static void initFormatStrings() {
644         synchronized (sLock) {
645             initFormatStringsLocked();
646         }
647     }
648 
initFormatStringsLocked()649     private static void initFormatStringsLocked() {
650         Resources r = Resources.getSystem();
651         Configuration cfg = r.getConfiguration();
652         if (sLastConfig == null || !sLastConfig.equals(cfg)) {
653             sLastConfig = cfg;
654             sStatusTimeFormat = java.text.DateFormat.getTimeInstance(java.text.DateFormat.SHORT);
655             sElapsedFormatMMSS = r.getString(com.android.internal.R.string.elapsed_time_short_format_mm_ss);
656             sElapsedFormatHMMSS = r.getString(com.android.internal.R.string.elapsed_time_short_format_h_mm_ss);
657         }
658     }
659 
660     /**
661      * Format a time so it appears like it would in the status bar clock.
662      * @deprecated use {@link #DateFormat.getTimeFormat(Context)} instead.
663      * @hide
664      */
timeString(long millis)665     public static final CharSequence timeString(long millis) {
666         synchronized (sLock) {
667             initFormatStringsLocked();
668             return sStatusTimeFormat.format(millis);
669         }
670     }
671 
672     /**
673      * Formats an elapsed time in the form "MM:SS" or "H:MM:SS"
674      * for display on the call-in-progress screen.
675      * @param elapsedSeconds the elapsed time in seconds.
676      */
formatElapsedTime(long elapsedSeconds)677     public static String formatElapsedTime(long elapsedSeconds) {
678         return formatElapsedTime(null, elapsedSeconds);
679     }
680 
681     /**
682      * Formats an elapsed time in the form "MM:SS" or "H:MM:SS"
683      * for display on the call-in-progress screen.
684      *
685      * @param recycle {@link StringBuilder} to recycle, if possible
686      * @param elapsedSeconds the elapsed time in seconds.
687      */
formatElapsedTime(StringBuilder recycle, long elapsedSeconds)688     public static String formatElapsedTime(StringBuilder recycle, long elapsedSeconds) {
689         initFormatStrings();
690 
691         long hours = 0;
692         long minutes = 0;
693         long seconds = 0;
694 
695         if (elapsedSeconds >= 3600) {
696             hours = elapsedSeconds / 3600;
697             elapsedSeconds -= hours * 3600;
698         }
699         if (elapsedSeconds >= 60) {
700             minutes = elapsedSeconds / 60;
701             elapsedSeconds -= minutes * 60;
702         }
703         seconds = elapsedSeconds;
704 
705         String result;
706         if (hours > 0) {
707             return formatElapsedTime(recycle, sElapsedFormatHMMSS, hours, minutes, seconds);
708         } else {
709             return formatElapsedTime(recycle, sElapsedFormatMMSS, minutes, seconds);
710         }
711     }
712 
713     /**
714      * Fast formatting of h:mm:ss
715      */
formatElapsedTime(StringBuilder recycle, String format, long hours, long minutes, long seconds)716     private static String formatElapsedTime(StringBuilder recycle, String format, long hours,
717             long minutes, long seconds) {
718         if (FAST_FORMAT_HMMSS.equals(format)) {
719             StringBuilder sb = recycle;
720             if (sb == null) {
721                 sb = new StringBuilder(8);
722             } else {
723                 sb.setLength(0);
724             }
725             sb.append(hours);
726             sb.append(TIME_SEPARATOR);
727             if (minutes < 10) {
728                 sb.append(TIME_PADDING);
729             } else {
730                 sb.append(toDigitChar(minutes / 10));
731             }
732             sb.append(toDigitChar(minutes % 10));
733             sb.append(TIME_SEPARATOR);
734             if (seconds < 10) {
735                 sb.append(TIME_PADDING);
736             } else {
737                 sb.append(toDigitChar(seconds / 10));
738             }
739             sb.append(toDigitChar(seconds % 10));
740             return sb.toString();
741         } else {
742             return String.format(format, hours, minutes, seconds);
743         }
744     }
745 
746     /**
747      * Fast formatting of m:ss
748      */
formatElapsedTime(StringBuilder recycle, String format, long minutes, long seconds)749     private static String formatElapsedTime(StringBuilder recycle, String format, long minutes,
750             long seconds) {
751         if (FAST_FORMAT_MMSS.equals(format)) {
752             StringBuilder sb = recycle;
753             if (sb == null) {
754                 sb = new StringBuilder(8);
755             } else {
756                 sb.setLength(0);
757             }
758             if (minutes < 10) {
759                 sb.append(TIME_PADDING);
760             } else {
761                 sb.append(toDigitChar(minutes / 10));
762             }
763             sb.append(toDigitChar(minutes % 10));
764             sb.append(TIME_SEPARATOR);
765             if (seconds < 10) {
766                 sb.append(TIME_PADDING);
767             } else {
768                 sb.append(toDigitChar(seconds / 10));
769             }
770             sb.append(toDigitChar(seconds % 10));
771             return sb.toString();
772         } else {
773             return String.format(format, minutes, seconds);
774         }
775     }
776 
toDigitChar(long digit)777     private static char toDigitChar(long digit) {
778         return (char) (digit + '0');
779     }
780 
781     /**
782      * Format a date / time such that if the then is on the same day as now, it shows
783      * just the time and if it's a different day, it shows just the date.
784      *
785      * <p>The parameters dateFormat and timeFormat should each be one of
786      * {@link java.text.DateFormat#DEFAULT},
787      * {@link java.text.DateFormat#FULL},
788      * {@link java.text.DateFormat#LONG},
789      * {@link java.text.DateFormat#MEDIUM}
790      * or
791      * {@link java.text.DateFormat#SHORT}
792      *
793      * @param then the date to format
794      * @param now the base time
795      * @param dateStyle how to format the date portion.
796      * @param timeStyle how to format the time portion.
797      */
formatSameDayTime(long then, long now, int dateStyle, int timeStyle)798     public static final CharSequence formatSameDayTime(long then, long now,
799             int dateStyle, int timeStyle) {
800         Calendar thenCal = new GregorianCalendar();
801         thenCal.setTimeInMillis(then);
802         Date thenDate = thenCal.getTime();
803         Calendar nowCal = new GregorianCalendar();
804         nowCal.setTimeInMillis(now);
805 
806         java.text.DateFormat f;
807 
808         if (thenCal.get(Calendar.YEAR) == nowCal.get(Calendar.YEAR)
809                 && thenCal.get(Calendar.MONTH) == nowCal.get(Calendar.MONTH)
810                 && thenCal.get(Calendar.DAY_OF_MONTH) == nowCal.get(Calendar.DAY_OF_MONTH)) {
811             f = java.text.DateFormat.getTimeInstance(timeStyle);
812         } else {
813             f = java.text.DateFormat.getDateInstance(dateStyle);
814         }
815         return f.format(thenDate);
816     }
817 
818     /**
819      * @hide
820      * @deprecated use {@link android.text.format.Time}
821      */
newCalendar(boolean zulu)822     public static Calendar newCalendar(boolean zulu)
823     {
824         if (zulu)
825             return Calendar.getInstance(TimeZone.getTimeZone("GMT"));
826 
827         return Calendar.getInstance();
828     }
829 
830     /**
831      * @return true if the supplied when is today else false
832      */
isToday(long when)833     public static boolean isToday(long when) {
834         Time time = new Time();
835         time.set(when);
836 
837         int thenYear = time.year;
838         int thenMonth = time.month;
839         int thenMonthDay = time.monthDay;
840 
841         time.set(System.currentTimeMillis());
842         return (thenYear == time.year)
843                 && (thenMonth == time.month)
844                 && (thenMonthDay == time.monthDay);
845     }
846 
847     /**
848      * @hide
849      * @deprecated use {@link android.text.format.Time}
850      * Return true if this date string is local time
851      */
isUTC(String s)852     public static boolean isUTC(String s)
853     {
854         if (s.length() == 16 && s.charAt(15) == 'Z') {
855             return true;
856         }
857         if (s.length() == 9 && s.charAt(8) == 'Z') {
858             // XXX not sure if this case possible/valid
859             return true;
860         }
861         return false;
862     }
863 
864     /**
865      * Return a string containing the date and time in RFC2445 format.
866      * Ensures that the time is written in UTC.  The Calendar class doesn't
867      * really help out with this, so this is slower than it ought to be.
868      *
869      * @param cal the date and time to write
870      * @hide
871      * @deprecated use {@link android.text.format.Time}
872      */
writeDateTime(Calendar cal)873     public static String writeDateTime(Calendar cal)
874     {
875         TimeZone tz = TimeZone.getTimeZone("GMT");
876         GregorianCalendar c = new GregorianCalendar(tz);
877         c.setTimeInMillis(cal.getTimeInMillis());
878         return writeDateTime(c, true);
879     }
880 
881     /**
882      * Return a string containing the date and time in RFC2445 format.
883      *
884      * @param cal the date and time to write
885      * @param zulu If the calendar is in UTC, pass true, and a Z will
886      * be written at the end as per RFC2445.  Otherwise, the time is
887      * considered in localtime.
888      * @hide
889      * @deprecated use {@link android.text.format.Time}
890      */
writeDateTime(Calendar cal, boolean zulu)891     public static String writeDateTime(Calendar cal, boolean zulu)
892     {
893         StringBuilder sb = new StringBuilder();
894         sb.ensureCapacity(16);
895         if (zulu) {
896             sb.setLength(16);
897             sb.setCharAt(15, 'Z');
898         } else {
899             sb.setLength(15);
900         }
901         return writeDateTime(cal, sb);
902     }
903 
904     /**
905      * Return a string containing the date and time in RFC2445 format.
906      *
907      * @param cal the date and time to write
908      * @param sb a StringBuilder to use.  It is assumed that setLength
909      *           has already been called on sb to the appropriate length
910      *           which is sb.setLength(zulu ? 16 : 15)
911      * @hide
912      * @deprecated use {@link android.text.format.Time}
913      */
writeDateTime(Calendar cal, StringBuilder sb)914     public static String writeDateTime(Calendar cal, StringBuilder sb)
915     {
916         int n;
917 
918         n = cal.get(Calendar.YEAR);
919         sb.setCharAt(3, (char)('0'+n%10));
920         n /= 10;
921         sb.setCharAt(2, (char)('0'+n%10));
922         n /= 10;
923         sb.setCharAt(1, (char)('0'+n%10));
924         n /= 10;
925         sb.setCharAt(0, (char)('0'+n%10));
926 
927         n = cal.get(Calendar.MONTH) + 1;
928         sb.setCharAt(5, (char)('0'+n%10));
929         n /= 10;
930         sb.setCharAt(4, (char)('0'+n%10));
931 
932         n = cal.get(Calendar.DAY_OF_MONTH);
933         sb.setCharAt(7, (char)('0'+n%10));
934         n /= 10;
935         sb.setCharAt(6, (char)('0'+n%10));
936 
937         sb.setCharAt(8, 'T');
938 
939         n = cal.get(Calendar.HOUR_OF_DAY);
940         sb.setCharAt(10, (char)('0'+n%10));
941         n /= 10;
942         sb.setCharAt(9, (char)('0'+n%10));
943 
944         n = cal.get(Calendar.MINUTE);
945         sb.setCharAt(12, (char)('0'+n%10));
946         n /= 10;
947         sb.setCharAt(11, (char)('0'+n%10));
948 
949         n = cal.get(Calendar.SECOND);
950         sb.setCharAt(14, (char)('0'+n%10));
951         n /= 10;
952         sb.setCharAt(13, (char)('0'+n%10));
953 
954         return sb.toString();
955     }
956 
957     /**
958      * @hide
959      * @deprecated use {@link android.text.format.Time}
960      */
assign(Calendar lval, Calendar rval)961     public static void assign(Calendar lval, Calendar rval)
962     {
963         // there should be a faster way.
964         lval.clear();
965         lval.setTimeInMillis(rval.getTimeInMillis());
966     }
967 
968     /**
969      * Formats a date or a time range according to the local conventions.
970      * <p>
971      * Note that this is a convenience method. Using it involves creating an
972      * internal {@link java.util.Formatter} instance on-the-fly, which is
973      * somewhat costly in terms of memory and time. This is probably acceptable
974      * if you use the method only rarely, but if you rely on it for formatting a
975      * large number of dates, consider creating and reusing your own
976      * {@link java.util.Formatter} instance and use the version of
977      * {@link #formatDateRange(Context, long, long, int) formatDateRange}
978      * that takes a {@link java.util.Formatter}.
979      *
980      * @param context the context is required only if the time is shown
981      * @param startMillis the start time in UTC milliseconds
982      * @param endMillis the end time in UTC milliseconds
983      * @param flags a bit mask of options See
984      * {@link #formatDateRange(Context, Formatter, long, long, int, String) formatDateRange}
985      * @return a string containing the formatted date/time range.
986      */
formatDateRange(Context context, long startMillis, long endMillis, int flags)987     public static String formatDateRange(Context context, long startMillis,
988             long endMillis, int flags) {
989         Formatter f = new Formatter(new StringBuilder(50), Locale.getDefault());
990         return formatDateRange(context, f, startMillis, endMillis, flags).toString();
991     }
992 
993     /**
994      * Formats a date or a time range according to the local conventions.
995      * <p>
996      * Note that this is a convenience method for formatting the date or
997      * time range in the local time zone. If you want to specify the time
998      * zone please use
999      * {@link #formatDateRange(Context, Formatter, long, long, int, String) formatDateRange}.
1000      *
1001      * @param context the context is required only if the time is shown
1002      * @param formatter the Formatter used for formatting the date range.
1003      * Note: be sure to call setLength(0) on StringBuilder passed to
1004      * the Formatter constructor unless you want the results to accumulate.
1005      * @param startMillis the start time in UTC milliseconds
1006      * @param endMillis the end time in UTC milliseconds
1007      * @param flags a bit mask of options See
1008      * {@link #formatDateRange(Context, Formatter, long, long, int, String) formatDateRange}
1009      * @return a string containing the formatted date/time range.
1010      */
formatDateRange(Context context, Formatter formatter, long startMillis, long endMillis, int flags)1011     public static Formatter formatDateRange(Context context, Formatter formatter, long startMillis,
1012             long endMillis, int flags) {
1013         return formatDateRange(context, formatter, startMillis, endMillis, flags, null);
1014     }
1015 
1016     /**
1017      * Formats a date or a time range according to the local conventions.
1018      *
1019      * <p>
1020      * Example output strings (date formats in these examples are shown using
1021      * the US date format convention but that may change depending on the
1022      * local settings):
1023      * <ul>
1024      *   <li>10:15am</li>
1025      *   <li>3:00pm - 4:00pm</li>
1026      *   <li>3pm - 4pm</li>
1027      *   <li>3PM - 4PM</li>
1028      *   <li>08:00 - 17:00</li>
1029      *   <li>Oct 9</li>
1030      *   <li>Tue, Oct 9</li>
1031      *   <li>October 9, 2007</li>
1032      *   <li>Oct 9 - 10</li>
1033      *   <li>Oct 9 - 10, 2007</li>
1034      *   <li>Oct 28 - Nov 3, 2007</li>
1035      *   <li>Dec 31, 2007 - Jan 1, 2008</li>
1036      *   <li>Oct 9, 8:00am - Oct 10, 5:00pm</li>
1037      *   <li>12/31/2007 - 01/01/2008</li>
1038      * </ul>
1039      *
1040      * <p>
1041      * The flags argument is a bitmask of options from the following list:
1042      *
1043      * <ul>
1044      *   <li>FORMAT_SHOW_TIME</li>
1045      *   <li>FORMAT_SHOW_WEEKDAY</li>
1046      *   <li>FORMAT_SHOW_YEAR</li>
1047      *   <li>FORMAT_NO_YEAR</li>
1048      *   <li>FORMAT_SHOW_DATE</li>
1049      *   <li>FORMAT_NO_MONTH_DAY</li>
1050      *   <li>FORMAT_12HOUR</li>
1051      *   <li>FORMAT_24HOUR</li>
1052      *   <li>FORMAT_CAP_AMPM</li>
1053      *   <li>FORMAT_NO_NOON</li>
1054      *   <li>FORMAT_CAP_NOON</li>
1055      *   <li>FORMAT_NO_MIDNIGHT</li>
1056      *   <li>FORMAT_CAP_MIDNIGHT</li>
1057      *   <li>FORMAT_UTC</li>
1058      *   <li>FORMAT_ABBREV_TIME</li>
1059      *   <li>FORMAT_ABBREV_WEEKDAY</li>
1060      *   <li>FORMAT_ABBREV_MONTH</li>
1061      *   <li>FORMAT_ABBREV_ALL</li>
1062      *   <li>FORMAT_NUMERIC_DATE</li>
1063      * </ul>
1064      *
1065      * <p>
1066      * If FORMAT_SHOW_TIME is set, the time is shown as part of the date range.
1067      * If the start and end time are the same, then just the start time is
1068      * shown.
1069      *
1070      * <p>
1071      * If FORMAT_SHOW_WEEKDAY is set, then the weekday is shown.
1072      *
1073      * <p>
1074      * If FORMAT_SHOW_YEAR is set, then the year is always shown.
1075      * If FORMAT_NO_YEAR is set, then the year is not shown.
1076      * If neither FORMAT_SHOW_YEAR nor FORMAT_NO_YEAR are set, then the year
1077      * is shown only if it is different from the current year, or if the start
1078      * and end dates fall on different years.  If both are set,
1079      * FORMAT_SHOW_YEAR takes precedence.
1080      *
1081      * <p>
1082      * Normally the date is shown unless the start and end day are the same.
1083      * If FORMAT_SHOW_DATE is set, then the date is always shown, even for
1084      * same day ranges.
1085      *
1086      * <p>
1087      * If FORMAT_NO_MONTH_DAY is set, then if the date is shown, just the
1088      * month name will be shown, not the day of the month.  For example,
1089      * "January, 2008" instead of "January 6 - 12, 2008".
1090      *
1091      * <p>
1092      * If FORMAT_CAP_AMPM is set and 12-hour time is used, then the "AM"
1093      * and "PM" are capitalized.  You should not use this flag
1094      * because in some locales these terms cannot be capitalized, and in
1095      * many others it doesn't make sense to do so even though it is possible.
1096      *
1097      * <p>
1098      * If FORMAT_NO_NOON is set and 12-hour time is used, then "12pm" is
1099      * shown instead of "noon".
1100      *
1101      * <p>
1102      * If FORMAT_CAP_NOON is set and 12-hour time is used, then "Noon" is
1103      * shown instead of "noon".  You should probably not use this flag
1104      * because in many locales it will not make sense to capitalize
1105      * the term.
1106      *
1107      * <p>
1108      * If FORMAT_NO_MIDNIGHT is set and 12-hour time is used, then "12am" is
1109      * shown instead of "midnight".
1110      *
1111      * <p>
1112      * If FORMAT_CAP_MIDNIGHT is set and 12-hour time is used, then "Midnight"
1113      * is shown instead of "midnight".  You should probably not use this
1114      * flag because in many locales it will not make sense to capitalize
1115      * the term.
1116      *
1117      * <p>
1118      * If FORMAT_12HOUR is set and the time is shown, then the time is
1119      * shown in the 12-hour time format. You should not normally set this.
1120      * Instead, let the time format be chosen automatically according to the
1121      * system settings. If both FORMAT_12HOUR and FORMAT_24HOUR are set, then
1122      * FORMAT_24HOUR takes precedence.
1123      *
1124      * <p>
1125      * If FORMAT_24HOUR is set and the time is shown, then the time is
1126      * shown in the 24-hour time format. You should not normally set this.
1127      * Instead, let the time format be chosen automatically according to the
1128      * system settings. If both FORMAT_12HOUR and FORMAT_24HOUR are set, then
1129      * FORMAT_24HOUR takes precedence.
1130      *
1131      * <p>
1132      * If FORMAT_UTC is set, then the UTC time zone is used for the start
1133      * and end milliseconds unless a time zone is specified. If a time zone
1134      * is specified it will be used regardless of the FORMAT_UTC flag.
1135      *
1136      * <p>
1137      * If FORMAT_ABBREV_TIME is set and 12-hour time format is used, then the
1138      * start and end times (if shown) are abbreviated by not showing the minutes
1139      * if they are zero.  For example, instead of "3:00pm" the time would be
1140      * abbreviated to "3pm".
1141      *
1142      * <p>
1143      * If FORMAT_ABBREV_WEEKDAY is set, then the weekday (if shown) is
1144      * abbreviated to a 3-letter string.
1145      *
1146      * <p>
1147      * If FORMAT_ABBREV_MONTH is set, then the month (if shown) is abbreviated
1148      * to a 3-letter string.
1149      *
1150      * <p>
1151      * If FORMAT_ABBREV_ALL is set, then the weekday and the month (if shown)
1152      * are abbreviated to 3-letter strings.
1153      *
1154      * <p>
1155      * If FORMAT_NUMERIC_DATE is set, then the date is shown in numeric format
1156      * instead of using the name of the month.  For example, "12/31/2008"
1157      * instead of "December 31, 2008".
1158      *
1159      * @param context the context is required only if the time is shown
1160      * @param formatter the Formatter used for formatting the date range.
1161      * Note: be sure to call setLength(0) on StringBuilder passed to
1162      * the Formatter constructor unless you want the results to accumulate.
1163      * @param startMillis the start time in UTC milliseconds
1164      * @param endMillis the end time in UTC milliseconds
1165      * @param flags a bit mask of options
1166      * @param timeZone the time zone to compute the string in. Use null for local
1167      * or if the FORMAT_UTC flag is being used.
1168      *
1169      * @return the formatter with the formatted date/time range appended to the string buffer.
1170      */
formatDateRange(Context context, Formatter formatter, long startMillis, long endMillis, int flags, String timeZone)1171     public static Formatter formatDateRange(Context context, Formatter formatter, long startMillis,
1172             long endMillis, int flags, String timeZone) {
1173         Resources res = Resources.getSystem();
1174         boolean showTime = (flags & FORMAT_SHOW_TIME) != 0;
1175         boolean showWeekDay = (flags & FORMAT_SHOW_WEEKDAY) != 0;
1176         boolean showYear = (flags & FORMAT_SHOW_YEAR) != 0;
1177         boolean noYear = (flags & FORMAT_NO_YEAR) != 0;
1178         boolean useUTC = (flags & FORMAT_UTC) != 0;
1179         boolean abbrevWeekDay = (flags & (FORMAT_ABBREV_WEEKDAY | FORMAT_ABBREV_ALL)) != 0;
1180         boolean abbrevMonth = (flags & (FORMAT_ABBREV_MONTH | FORMAT_ABBREV_ALL)) != 0;
1181         boolean noMonthDay = (flags & FORMAT_NO_MONTH_DAY) != 0;
1182         boolean numericDate = (flags & FORMAT_NUMERIC_DATE) != 0;
1183 
1184         // If we're getting called with a single instant in time (from
1185         // e.g. formatDateTime(), below), then we can skip a lot of
1186         // computation below that'd otherwise be thrown out.
1187         boolean isInstant = (startMillis == endMillis);
1188 
1189         Time startDate;
1190         if (timeZone != null) {
1191             startDate = new Time(timeZone);
1192         } else if (useUTC) {
1193             startDate = new Time(Time.TIMEZONE_UTC);
1194         } else {
1195             startDate = new Time();
1196         }
1197         startDate.set(startMillis);
1198 
1199         Time endDate;
1200         int dayDistance;
1201         if (isInstant) {
1202             endDate = startDate;
1203             dayDistance = 0;
1204         } else {
1205             if (timeZone != null) {
1206                 endDate = new Time(timeZone);
1207             } else if (useUTC) {
1208                 endDate = new Time(Time.TIMEZONE_UTC);
1209             } else {
1210                 endDate = new Time();
1211             }
1212             endDate.set(endMillis);
1213             int startJulianDay = Time.getJulianDay(startMillis, startDate.gmtoff);
1214             int endJulianDay = Time.getJulianDay(endMillis, endDate.gmtoff);
1215             dayDistance = endJulianDay - startJulianDay;
1216         }
1217 
1218         // If the end date ends at 12am at the beginning of a day,
1219         // then modify it to make it look like it ends at midnight on
1220         // the previous day.  This will allow us to display "8pm - midnight",
1221         // for example, instead of "Nov 10, 8pm - Nov 11, 12am". But we only do
1222         // this if it is midnight of the same day as the start date because
1223         // for multiple-day events, an end time of "midnight on Nov 11" is
1224         // ambiguous and confusing (is that midnight the start of Nov 11, or
1225         // the end of Nov 11?).
1226         // If we are not showing the time then also adjust the end date
1227         // for multiple-day events.  This is to allow us to display, for
1228         // example, "Nov 10 -11" for an event with a start date of Nov 10
1229         // and an end date of Nov 12 at 00:00.
1230         // If the start and end time are the same, then skip this and don't
1231         // adjust the date.
1232         if (!isInstant
1233             && (endDate.hour | endDate.minute | endDate.second) == 0
1234             && (!showTime || dayDistance <= 1)) {
1235             endDate.monthDay -= 1;
1236             endDate.normalize(true /* ignore isDst */);
1237         }
1238 
1239         int startDay = startDate.monthDay;
1240         int startMonthNum = startDate.month;
1241         int startYear = startDate.year;
1242 
1243         int endDay = endDate.monthDay;
1244         int endMonthNum = endDate.month;
1245         int endYear = endDate.year;
1246 
1247         String startWeekDayString = "";
1248         String endWeekDayString = "";
1249         if (showWeekDay) {
1250             String weekDayFormat = "";
1251             if (abbrevWeekDay) {
1252                 weekDayFormat = ABBREV_WEEKDAY_FORMAT;
1253             } else {
1254                 weekDayFormat = WEEKDAY_FORMAT;
1255             }
1256             startWeekDayString = startDate.format(weekDayFormat);
1257             endWeekDayString = isInstant ? startWeekDayString : endDate.format(weekDayFormat);
1258         }
1259 
1260         String startTimeString = "";
1261         String endTimeString = "";
1262         if (showTime) {
1263             String startTimeFormat = "";
1264             String endTimeFormat = "";
1265             boolean force24Hour = (flags & FORMAT_24HOUR) != 0;
1266             boolean force12Hour = (flags & FORMAT_12HOUR) != 0;
1267             boolean use24Hour;
1268             if (force24Hour) {
1269                 use24Hour = true;
1270             } else if (force12Hour) {
1271                 use24Hour = false;
1272             } else {
1273                 use24Hour = DateFormat.is24HourFormat(context);
1274             }
1275             if (use24Hour) {
1276                 startTimeFormat = endTimeFormat =
1277                     res.getString(com.android.internal.R.string.hour_minute_24);
1278             } else {
1279                 boolean abbrevTime = (flags & (FORMAT_ABBREV_TIME | FORMAT_ABBREV_ALL)) != 0;
1280                 boolean capAMPM = (flags & FORMAT_CAP_AMPM) != 0;
1281                 boolean noNoon = (flags & FORMAT_NO_NOON) != 0;
1282                 boolean capNoon = (flags & FORMAT_CAP_NOON) != 0;
1283                 boolean noMidnight = (flags & FORMAT_NO_MIDNIGHT) != 0;
1284                 boolean capMidnight = (flags & FORMAT_CAP_MIDNIGHT) != 0;
1285 
1286                 boolean startOnTheHour = startDate.minute == 0 && startDate.second == 0;
1287                 boolean endOnTheHour = endDate.minute == 0 && endDate.second == 0;
1288                 if (abbrevTime && startOnTheHour) {
1289                     if (capAMPM) {
1290                         startTimeFormat = res.getString(com.android.internal.R.string.hour_cap_ampm);
1291                     } else {
1292                         startTimeFormat = res.getString(com.android.internal.R.string.hour_ampm);
1293                     }
1294                 } else {
1295                     if (capAMPM) {
1296                         startTimeFormat = res.getString(com.android.internal.R.string.hour_minute_cap_ampm);
1297                     } else {
1298                         startTimeFormat = res.getString(com.android.internal.R.string.hour_minute_ampm);
1299                     }
1300                 }
1301 
1302                 // Don't waste time on setting endTimeFormat when
1303                 // we're dealing with an instant, where we'll never
1304                 // need the end point.  (It's the same as the start
1305                 // point)
1306                 if (!isInstant) {
1307                     if (abbrevTime && endOnTheHour) {
1308                         if (capAMPM) {
1309                             endTimeFormat = res.getString(com.android.internal.R.string.hour_cap_ampm);
1310                         } else {
1311                             endTimeFormat = res.getString(com.android.internal.R.string.hour_ampm);
1312                         }
1313                     } else {
1314                         if (capAMPM) {
1315                             endTimeFormat = res.getString(com.android.internal.R.string.hour_minute_cap_ampm);
1316                         } else {
1317                             endTimeFormat = res.getString(com.android.internal.R.string.hour_minute_ampm);
1318                         }
1319                     }
1320 
1321                     if (endDate.hour == 12 && endOnTheHour && !noNoon) {
1322                         if (capNoon) {
1323                             endTimeFormat = res.getString(com.android.internal.R.string.Noon);
1324                         } else {
1325                             endTimeFormat = res.getString(com.android.internal.R.string.noon);
1326                         }
1327                     } else if (endDate.hour == 0 && endOnTheHour && !noMidnight) {
1328                         if (capMidnight) {
1329                             endTimeFormat = res.getString(com.android.internal.R.string.Midnight);
1330                         } else {
1331                             endTimeFormat = res.getString(com.android.internal.R.string.midnight);
1332                         }
1333                     }
1334                 }
1335 
1336                 if (startDate.hour == 12 && startOnTheHour && !noNoon) {
1337                     if (capNoon) {
1338                         startTimeFormat = res.getString(com.android.internal.R.string.Noon);
1339                     } else {
1340                         startTimeFormat = res.getString(com.android.internal.R.string.noon);
1341                     }
1342                     // Don't show the start time starting at midnight.  Show
1343                     // 12am instead.
1344                 }
1345             }
1346 
1347             startTimeString = startDate.format(startTimeFormat);
1348             endTimeString = isInstant ? startTimeString : endDate.format(endTimeFormat);
1349         }
1350 
1351         // Show the year if the user specified FORMAT_SHOW_YEAR or if
1352         // the starting and end years are different from each other
1353         // or from the current year.  But don't show the year if the
1354         // user specified FORMAT_NO_YEAR.
1355         if (showYear) {
1356             // No code... just a comment for clarity.  Keep showYear
1357             // on, as they enabled it with FORMAT_SHOW_YEAR.  This
1358             // takes precedence over them setting FORMAT_NO_YEAR.
1359         } else if (noYear) {
1360             // They explicitly didn't want a year.
1361             showYear = false;
1362         } else if (startYear != endYear) {
1363             showYear = true;
1364         } else {
1365             // Show the year if it's not equal to the current year.
1366             Time currentTime = new Time();
1367             currentTime.setToNow();
1368             showYear = startYear != currentTime.year;
1369         }
1370 
1371         String defaultDateFormat, fullFormat, dateRange;
1372         if (numericDate) {
1373             defaultDateFormat = res.getString(com.android.internal.R.string.numeric_date);
1374         } else if (showYear) {
1375             if (abbrevMonth) {
1376                 if (noMonthDay) {
1377                     defaultDateFormat = res.getString(com.android.internal.R.string.abbrev_month_year);
1378                 } else {
1379                     defaultDateFormat = res.getString(com.android.internal.R.string.abbrev_month_day_year);
1380                 }
1381             } else {
1382                 if (noMonthDay) {
1383                     defaultDateFormat = res.getString(com.android.internal.R.string.month_year);
1384                 } else {
1385                     defaultDateFormat = res.getString(com.android.internal.R.string.month_day_year);
1386                 }
1387             }
1388         } else {
1389             if (abbrevMonth) {
1390                 if (noMonthDay) {
1391                     defaultDateFormat = res.getString(com.android.internal.R.string.abbrev_month);
1392                 } else {
1393                     defaultDateFormat = res.getString(com.android.internal.R.string.abbrev_month_day);
1394                 }
1395             } else {
1396                 if (noMonthDay) {
1397                     defaultDateFormat = res.getString(com.android.internal.R.string.month);
1398                 } else {
1399                     defaultDateFormat = res.getString(com.android.internal.R.string.month_day);
1400                 }
1401             }
1402         }
1403 
1404         if (showWeekDay) {
1405             if (showTime) {
1406                 fullFormat = res.getString(com.android.internal.R.string.wday1_date1_time1_wday2_date2_time2);
1407             } else {
1408                 fullFormat = res.getString(com.android.internal.R.string.wday1_date1_wday2_date2);
1409             }
1410         } else {
1411             if (showTime) {
1412                 fullFormat = res.getString(com.android.internal.R.string.date1_time1_date2_time2);
1413             } else {
1414                 fullFormat = res.getString(com.android.internal.R.string.date1_date2);
1415             }
1416         }
1417 
1418         if (noMonthDay && startMonthNum == endMonthNum) {
1419             // Example: "January, 2008"
1420             return formatter.format("%s", startDate.format(defaultDateFormat));
1421         }
1422 
1423         if (startYear != endYear || noMonthDay) {
1424             // Different year or we are not showing the month day number.
1425             // Example: "December 31, 2007 - January 1, 2008"
1426             // Or: "January - February, 2008"
1427             String startDateString = startDate.format(defaultDateFormat);
1428             String endDateString = endDate.format(defaultDateFormat);
1429 
1430             // The values that are used in a fullFormat string are specified
1431             // by position.
1432             return formatter.format(fullFormat,
1433                     startWeekDayString, startDateString, startTimeString,
1434                     endWeekDayString, endDateString, endTimeString);
1435         }
1436 
1437         // Get the month, day, and year strings for the start and end dates
1438         String monthFormat;
1439         if (numericDate) {
1440             monthFormat = NUMERIC_MONTH_FORMAT;
1441         } else if (abbrevMonth) {
1442             monthFormat =
1443                 res.getString(com.android.internal.R.string.short_format_month);
1444         } else {
1445             monthFormat = MONTH_FORMAT;
1446         }
1447         String startMonthString = startDate.format(monthFormat);
1448         String startMonthDayString = startDate.format(MONTH_DAY_FORMAT);
1449         String startYearString = startDate.format(YEAR_FORMAT);
1450 
1451         String endMonthString = isInstant ? null : endDate.format(monthFormat);
1452         String endMonthDayString = isInstant ? null : endDate.format(MONTH_DAY_FORMAT);
1453         String endYearString = isInstant ? null : endDate.format(YEAR_FORMAT);
1454 
1455         if (startMonthNum != endMonthNum) {
1456             // Same year, different month.
1457             // Example: "October 28 - November 3"
1458             // or: "Wed, Oct 31 - Sat, Nov 3, 2007"
1459             // or: "Oct 31, 8am - Sat, Nov 3, 2007, 5pm"
1460 
1461             int index = 0;
1462             if (showWeekDay) index = 1;
1463             if (showYear) index += 2;
1464             if (showTime) index += 4;
1465             if (numericDate) index += 8;
1466             int resId = sameYearTable[index];
1467             fullFormat = res.getString(resId);
1468 
1469             // The values that are used in a fullFormat string are specified
1470             // by position.
1471             return formatter.format(fullFormat,
1472                     startWeekDayString, startMonthString, startMonthDayString,
1473                     startYearString, startTimeString,
1474                     endWeekDayString, endMonthString, endMonthDayString,
1475                     endYearString, endTimeString);
1476         }
1477 
1478         if (startDay != endDay) {
1479             // Same month, different day.
1480             int index = 0;
1481             if (showWeekDay) index = 1;
1482             if (showYear) index += 2;
1483             if (showTime) index += 4;
1484             if (numericDate) index += 8;
1485             int resId = sameMonthTable[index];
1486             fullFormat = res.getString(resId);
1487 
1488             // The values that are used in a fullFormat string are specified
1489             // by position.
1490             return formatter.format(fullFormat,
1491                     startWeekDayString, startMonthString, startMonthDayString,
1492                     startYearString, startTimeString,
1493                     endWeekDayString, endMonthString, endMonthDayString,
1494                     endYearString, endTimeString);
1495         }
1496 
1497         // Same start and end day
1498         boolean showDate = (flags & FORMAT_SHOW_DATE) != 0;
1499 
1500         // If nothing was specified, then show the date.
1501         if (!showTime && !showDate && !showWeekDay) showDate = true;
1502 
1503         // Compute the time string (example: "10:00 - 11:00 am")
1504         String timeString = "";
1505         if (showTime) {
1506             // If the start and end time are the same, then just show the
1507             // start time.
1508             if (isInstant) {
1509                 // Same start and end time.
1510                 // Example: "10:15 AM"
1511                 timeString = startTimeString;
1512             } else {
1513                 // Example: "10:00 - 11:00 am"
1514                 String timeFormat = res.getString(com.android.internal.R.string.time1_time2);
1515                 // Don't use the user supplied Formatter because the result will pollute the buffer.
1516                 timeString = String.format(timeFormat, startTimeString, endTimeString);
1517             }
1518         }
1519 
1520         // Figure out which full format to use.
1521         fullFormat = "";
1522         String dateString = "";
1523         if (showDate) {
1524             dateString = startDate.format(defaultDateFormat);
1525             if (showWeekDay) {
1526                 if (showTime) {
1527                     // Example: "10:00 - 11:00 am, Tue, Oct 9"
1528                     fullFormat = res.getString(com.android.internal.R.string.time_wday_date);
1529                 } else {
1530                     // Example: "Tue, Oct 9"
1531                     fullFormat = res.getString(com.android.internal.R.string.wday_date);
1532                 }
1533             } else {
1534                 if (showTime) {
1535                     // Example: "10:00 - 11:00 am, Oct 9"
1536                     fullFormat = res.getString(com.android.internal.R.string.time_date);
1537                 } else {
1538                     // Example: "Oct 9"
1539                     return formatter.format("%s", dateString);
1540                 }
1541             }
1542         } else if (showWeekDay) {
1543             if (showTime) {
1544                 // Example: "10:00 - 11:00 am, Tue"
1545                 fullFormat = res.getString(com.android.internal.R.string.time_wday);
1546             } else {
1547                 // Example: "Tue"
1548                 return formatter.format("%s", startWeekDayString);
1549             }
1550         } else if (showTime) {
1551             return formatter.format("%s", timeString);
1552         }
1553 
1554         // The values that are used in a fullFormat string are specified
1555         // by position.
1556         return formatter.format(fullFormat, timeString, startWeekDayString, dateString);
1557     }
1558 
1559     /**
1560      * Formats a date or a time according to the local conventions. There are
1561      * lots of options that allow the caller to control, for example, if the
1562      * time is shown, if the day of the week is shown, if the month name is
1563      * abbreviated, if noon is shown instead of 12pm, and so on. For the
1564      * complete list of options, see the documentation for
1565      * {@link #formatDateRange}.
1566      * <p>
1567      * Example output strings (date formats in these examples are shown using
1568      * the US date format convention but that may change depending on the
1569      * local settings):
1570      * <ul>
1571      *   <li>10:15am</li>
1572      *   <li>3:00pm</li>
1573      *   <li>3pm</li>
1574      *   <li>3PM</li>
1575      *   <li>08:00</li>
1576      *   <li>17:00</li>
1577      *   <li>noon</li>
1578      *   <li>Noon</li>
1579      *   <li>midnight</li>
1580      *   <li>Midnight</li>
1581      *   <li>Oct 31</li>
1582      *   <li>Oct 31, 2007</li>
1583      *   <li>October 31, 2007</li>
1584      *   <li>10am, Oct 31</li>
1585      *   <li>17:00, Oct 31</li>
1586      *   <li>Wed</li>
1587      *   <li>Wednesday</li>
1588      *   <li>10am, Wed, Oct 31</li>
1589      *   <li>Wed, Oct 31</li>
1590      *   <li>Wednesday, Oct 31</li>
1591      *   <li>Wed, Oct 31, 2007</li>
1592      *   <li>Wed, October 31</li>
1593      *   <li>10/31/2007</li>
1594      * </ul>
1595      *
1596      * @param context the context is required only if the time is shown
1597      * @param millis a point in time in UTC milliseconds
1598      * @param flags a bit mask of formatting options
1599      * @return a string containing the formatted date/time.
1600      */
formatDateTime(Context context, long millis, int flags)1601     public static String formatDateTime(Context context, long millis, int flags) {
1602         return formatDateRange(context, millis, millis, flags);
1603     }
1604 
1605     /**
1606      * @return a relative time string to display the time expressed by millis.  Times
1607      * are counted starting at midnight, which means that assuming that the current
1608      * time is March 31st, 0:30:
1609      * <ul>
1610      *   <li>"millis=0:10 today" will be displayed as "0:10"</li>
1611      *   <li>"millis=11:30pm the day before" will be displayed as "Mar 30"</li>
1612      * </ul>
1613      * If the given millis is in a different year, then the full date is
1614      * returned in numeric format (e.g., "10/12/2008").
1615      *
1616      * @param withPreposition If true, the string returned will include the correct
1617      * preposition ("at 9:20am", "on 10/12/2008" or "on May 29").
1618      */
getRelativeTimeSpanString(Context c, long millis, boolean withPreposition)1619     public static CharSequence getRelativeTimeSpanString(Context c, long millis,
1620             boolean withPreposition) {
1621 
1622         String result;
1623         long now = System.currentTimeMillis();
1624         long span = now - millis;
1625 
1626         synchronized (DateUtils.class) {
1627             if (sNowTime == null) {
1628                 sNowTime = new Time();
1629             }
1630 
1631             if (sThenTime == null) {
1632                 sThenTime = new Time();
1633             }
1634 
1635             sNowTime.set(now);
1636             sThenTime.set(millis);
1637 
1638             int prepositionId;
1639             if (span < DAY_IN_MILLIS && sNowTime.weekDay == sThenTime.weekDay) {
1640                 // Same day
1641                 int flags = FORMAT_SHOW_TIME;
1642                 result = formatDateRange(c, millis, millis, flags);
1643                 prepositionId = R.string.preposition_for_time;
1644             } else if (sNowTime.year != sThenTime.year) {
1645                 // Different years
1646                 int flags = FORMAT_SHOW_DATE | FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE;
1647                 result = formatDateRange(c, millis, millis, flags);
1648 
1649                 // This is a date (like "10/31/2008" so use the date preposition)
1650                 prepositionId = R.string.preposition_for_date;
1651             } else {
1652                 // Default
1653                 int flags = FORMAT_SHOW_DATE | FORMAT_ABBREV_MONTH;
1654                 result = formatDateRange(c, millis, millis, flags);
1655                 prepositionId = R.string.preposition_for_date;
1656             }
1657             if (withPreposition) {
1658                 Resources res = c.getResources();
1659                 result = res.getString(prepositionId, result);
1660             }
1661         }
1662         return result;
1663     }
1664 
1665     /**
1666      * Convenience function to return relative time string without preposition.
1667      * @param c context for resources
1668      * @param millis time in milliseconds
1669      * @return {@link CharSequence} containing relative time.
1670      * @see #getRelativeTimeSpanString(Context, long, boolean)
1671      */
getRelativeTimeSpanString(Context c, long millis)1672     public static CharSequence getRelativeTimeSpanString(Context c, long millis) {
1673         return getRelativeTimeSpanString(c, millis, false /* no preposition */);
1674     }
1675 
1676     private static Time sNowTime;
1677     private static Time sThenTime;
1678 }
1679