• 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 android.annotation.UnsupportedAppUsage;
20 import android.content.Context;
21 import android.content.res.Configuration;
22 import android.content.res.Resources;
23 import android.icu.text.MeasureFormat;
24 import android.icu.text.MeasureFormat.FormatWidth;
25 import android.icu.util.Measure;
26 import android.icu.util.MeasureUnit;
27 
28 import com.android.internal.R;
29 
30 import libcore.icu.DateIntervalFormat;
31 import libcore.icu.LocaleData;
32 import libcore.icu.RelativeDateTimeFormatter;
33 
34 import java.io.IOException;
35 import java.util.Calendar;
36 import java.util.Date;
37 import java.util.Formatter;
38 import java.util.GregorianCalendar;
39 import java.util.Locale;
40 import java.util.TimeZone;
41 
42 /**
43  * This class contains various date-related utilities for creating text for things like
44  * elapsed time and date ranges, strings for days of the week and months, and AM/PM text etc.
45  */
46 public class DateUtils
47 {
48     private static final Object sLock = new Object();
49     private static Configuration sLastConfig;
50     private static String sElapsedFormatMMSS;
51     private static String sElapsedFormatHMMSS;
52 
53     public static final long SECOND_IN_MILLIS = 1000;
54     public static final long MINUTE_IN_MILLIS = SECOND_IN_MILLIS * 60;
55     public static final long HOUR_IN_MILLIS = MINUTE_IN_MILLIS * 60;
56     public static final long DAY_IN_MILLIS = HOUR_IN_MILLIS * 24;
57     public static final long WEEK_IN_MILLIS = DAY_IN_MILLIS * 7;
58     /**
59      * This constant is actually the length of 364 days, not of a year!
60      */
61     public static final long YEAR_IN_MILLIS = WEEK_IN_MILLIS * 52;
62 
63     // The following FORMAT_* symbols are used for specifying the format of
64     // dates and times in the formatDateRange method.
65     public static final int FORMAT_SHOW_TIME = 0x00001;
66     public static final int FORMAT_SHOW_WEEKDAY = 0x00002;
67     public static final int FORMAT_SHOW_YEAR = 0x00004;
68     public static final int FORMAT_NO_YEAR = 0x00008;
69     public static final int FORMAT_SHOW_DATE = 0x00010;
70     public static final int FORMAT_NO_MONTH_DAY = 0x00020;
71     @Deprecated
72     public static final int FORMAT_12HOUR = 0x00040;
73     @Deprecated
74     public static final int FORMAT_24HOUR = 0x00080;
75     @Deprecated
76     public static final int FORMAT_CAP_AMPM = 0x00100;
77     public static final int FORMAT_NO_NOON = 0x00200;
78     @Deprecated
79     public static final int FORMAT_CAP_NOON = 0x00400;
80     public static final int FORMAT_NO_MIDNIGHT = 0x00800;
81     @Deprecated
82     public static final int FORMAT_CAP_MIDNIGHT = 0x01000;
83     /**
84      * @deprecated Use
85      * {@link #formatDateRange(Context, Formatter, long, long, int, String) formatDateRange}
86      * and pass in {@link Time#TIMEZONE_UTC Time.TIMEZONE_UTC} for the timeZone instead.
87      */
88     @Deprecated
89     public static final int FORMAT_UTC = 0x02000;
90     public static final int FORMAT_ABBREV_TIME = 0x04000;
91     public static final int FORMAT_ABBREV_WEEKDAY = 0x08000;
92     public static final int FORMAT_ABBREV_MONTH = 0x10000;
93     public static final int FORMAT_NUMERIC_DATE = 0x20000;
94     public static final int FORMAT_ABBREV_RELATIVE = 0x40000;
95     public static final int FORMAT_ABBREV_ALL = 0x80000;
96     @Deprecated
97     public static final int FORMAT_CAP_NOON_MIDNIGHT = (FORMAT_CAP_NOON | FORMAT_CAP_MIDNIGHT);
98     @Deprecated
99     public static final int FORMAT_NO_NOON_MIDNIGHT = (FORMAT_NO_NOON | FORMAT_NO_MIDNIGHT);
100 
101     // Date and time format strings that are constant and don't need to be
102     // translated.
103     /**
104      * This is not actually the preferred 24-hour date format in all locales.
105      * @deprecated Use {@link java.text.SimpleDateFormat} instead.
106      */
107     @Deprecated
108     public static final String HOUR_MINUTE_24 = "%H:%M";
109     public static final String MONTH_FORMAT = "%B";
110     /**
111      * This is not actually a useful month name in all locales.
112      * @deprecated Use {@link java.text.SimpleDateFormat} instead.
113      */
114     @Deprecated
115     public static final String ABBREV_MONTH_FORMAT = "%b";
116     public static final String NUMERIC_MONTH_FORMAT = "%m";
117     public static final String MONTH_DAY_FORMAT = "%-d";
118     public static final String YEAR_FORMAT = "%Y";
119     public static final String YEAR_FORMAT_TWO_DIGITS = "%g";
120     public static final String WEEKDAY_FORMAT = "%A";
121     public static final String ABBREV_WEEKDAY_FORMAT = "%a";
122 
123     /** @deprecated Do not use. */
124     @Deprecated
125     public static final int[] sameYearTable = null;
126 
127     /** @deprecated Do not use. */
128     @Deprecated
129     public static final int[] sameMonthTable = null;
130 
131     /**
132      * Request the full spelled-out name. For use with the 'abbrev' parameter of
133      * {@link #getDayOfWeekString} and {@link #getMonthString}.
134      *
135      * @more <p>
136      *       e.g. "Sunday" or "January"
137      * @deprecated Use {@link java.text.SimpleDateFormat} instead.
138      */
139     @Deprecated
140     public static final int LENGTH_LONG = 10;
141 
142     /**
143      * Request an abbreviated version of the name. For use with the 'abbrev'
144      * parameter of {@link #getDayOfWeekString} and {@link #getMonthString}.
145      *
146      * @more <p>
147      *       e.g. "Sun" or "Jan"
148      * @deprecated Use {@link java.text.SimpleDateFormat} instead.
149      */
150     @Deprecated
151     public static final int LENGTH_MEDIUM = 20;
152 
153     /**
154      * Request a shorter abbreviated version of the name.
155      * For use with the 'abbrev' parameter of {@link #getDayOfWeekString} and {@link #getMonthString}.
156      * @more
157      * <p>e.g. "Su" or "Jan"
158      * <p>In most languages, the results returned for LENGTH_SHORT will be the same as
159      * the results returned for {@link #LENGTH_MEDIUM}.
160      * @deprecated Use {@link java.text.SimpleDateFormat} instead.
161      */
162     @Deprecated
163     public static final int LENGTH_SHORT = 30;
164 
165     /**
166      * Request an even shorter abbreviated version of the name.
167      * Do not use this.  Currently this will always return the same result
168      * as {@link #LENGTH_SHORT}.
169      * @deprecated Use {@link java.text.SimpleDateFormat} instead.
170      */
171     @Deprecated
172     public static final int LENGTH_SHORTER = 40;
173 
174     /**
175      * Request an even shorter abbreviated version of the name.
176      * For use with the 'abbrev' parameter of {@link #getDayOfWeekString} and {@link #getMonthString}.
177      * @more
178      * <p>e.g. "S", "T", "T" or "J"
179      * <p>In some languages, the results returned for LENGTH_SHORTEST will be the same as
180      * the results returned for {@link #LENGTH_SHORT}.
181      * @deprecated Use {@link java.text.SimpleDateFormat} instead.
182      */
183     @Deprecated
184     public static final int LENGTH_SHORTEST = 50;
185 
186     /**
187      * Return a string for the day of the week.
188      * @param dayOfWeek One of {@link Calendar#SUNDAY Calendar.SUNDAY},
189      *               {@link Calendar#MONDAY Calendar.MONDAY}, etc.
190      * @param abbrev One of {@link #LENGTH_LONG}, {@link #LENGTH_SHORT},
191      *               {@link #LENGTH_MEDIUM}, or {@link #LENGTH_SHORTEST}.
192      *               Note that in most languages, {@link #LENGTH_SHORT}
193      *               will return the same as {@link #LENGTH_MEDIUM}.
194      *               Undefined lengths will return {@link #LENGTH_MEDIUM}
195      *               but may return something different in the future.
196      * @throws IndexOutOfBoundsException if the dayOfWeek is out of bounds.
197      * @deprecated Use {@link java.text.SimpleDateFormat} instead.
198      */
199     @Deprecated
getDayOfWeekString(int dayOfWeek, int abbrev)200     public static String getDayOfWeekString(int dayOfWeek, int abbrev) {
201         LocaleData d = LocaleData.get(Locale.getDefault());
202         String[] names;
203         switch (abbrev) {
204             case LENGTH_LONG:       names = d.longWeekdayNames;  break;
205             case LENGTH_MEDIUM:     names = d.shortWeekdayNames; break;
206             case LENGTH_SHORT:      names = d.shortWeekdayNames; break; // TODO
207             case LENGTH_SHORTER:    names = d.shortWeekdayNames; break; // TODO
208             case LENGTH_SHORTEST:   names = d.tinyWeekdayNames;  break;
209             default:                names = d.shortWeekdayNames; break;
210         }
211         return names[dayOfWeek];
212     }
213 
214     /**
215      * Return a localized string for AM or PM.
216      * @param ampm Either {@link Calendar#AM Calendar.AM} or {@link Calendar#PM Calendar.PM}.
217      * @throws IndexOutOfBoundsException if the ampm is out of bounds.
218      * @return Localized version of "AM" or "PM".
219      * @deprecated Use {@link java.text.SimpleDateFormat} instead.
220      */
221     @Deprecated
getAMPMString(int ampm)222     public static String getAMPMString(int ampm) {
223         return LocaleData.get(Locale.getDefault()).amPm[ampm - Calendar.AM];
224     }
225 
226     /**
227      * Return a localized string for the month of the year.
228      * @param month One of {@link Calendar#JANUARY Calendar.JANUARY},
229      *               {@link Calendar#FEBRUARY Calendar.FEBRUARY}, etc.
230      * @param abbrev One of {@link #LENGTH_LONG}, {@link #LENGTH_MEDIUM},
231      *               or {@link #LENGTH_SHORTEST}.
232      *               Undefined lengths will return {@link #LENGTH_MEDIUM}
233      *               but may return something different in the future.
234      * @return Localized month of the year.
235      * @deprecated Use {@link java.text.SimpleDateFormat} instead.
236      */
237     @Deprecated
getMonthString(int month, int abbrev)238     public static String getMonthString(int month, int abbrev) {
239         LocaleData d = LocaleData.get(Locale.getDefault());
240         String[] names;
241         switch (abbrev) {
242             case LENGTH_LONG:       names = d.longMonthNames;  break;
243             case LENGTH_MEDIUM:     names = d.shortMonthNames; break;
244             case LENGTH_SHORT:      names = d.shortMonthNames; break;
245             case LENGTH_SHORTER:    names = d.shortMonthNames; break;
246             case LENGTH_SHORTEST:   names = d.tinyMonthNames;  break;
247             default:                names = d.shortMonthNames; break;
248         }
249         return names[month];
250     }
251 
252     /**
253      * Returns a string describing the elapsed time since startTime.
254      * <p>
255      * The minimum timespan to report is set to {@link #MINUTE_IN_MILLIS}.
256      * @param startTime some time in the past.
257      * @return a String object containing the elapsed time.
258      * @see #getRelativeTimeSpanString(long, long, long)
259      */
getRelativeTimeSpanString(long startTime)260     public static CharSequence getRelativeTimeSpanString(long startTime) {
261         return getRelativeTimeSpanString(startTime, System.currentTimeMillis(), MINUTE_IN_MILLIS);
262     }
263 
264     /**
265      * Returns a string describing 'time' as a time relative to 'now'.
266      * <p>
267      * Time spans in the past are formatted like "42 minutes ago".
268      * Time spans in the future are formatted like "In 42 minutes".
269      *
270      * @param time the time to describe, in milliseconds
271      * @param now the current time in milliseconds
272      * @param minResolution the minimum timespan to report. For example, a time 3 seconds in the
273      *     past will be reported as "0 minutes ago" if this is set to MINUTE_IN_MILLIS. Pass one of
274      *     0, MINUTE_IN_MILLIS, HOUR_IN_MILLIS, DAY_IN_MILLIS, WEEK_IN_MILLIS
275      */
getRelativeTimeSpanString(long time, long now, long minResolution)276     public static CharSequence getRelativeTimeSpanString(long time, long now, long minResolution) {
277         int flags = FORMAT_SHOW_DATE | FORMAT_SHOW_YEAR | FORMAT_ABBREV_MONTH;
278         return getRelativeTimeSpanString(time, now, minResolution, flags);
279     }
280 
281     /**
282      * Returns a string describing 'time' as a time relative to 'now'.
283      * <p>
284      * Time spans in the past are formatted like "42 minutes ago". Time spans in
285      * the future are formatted like "In 42 minutes".
286      * <p>
287      * Can use {@link #FORMAT_ABBREV_RELATIVE} flag to use abbreviated relative
288      * times, like "42 mins ago".
289      *
290      * @param time the time to describe, in milliseconds
291      * @param now the current time in milliseconds
292      * @param minResolution the minimum timespan to report. For example, a time
293      *            3 seconds in the past will be reported as "0 minutes ago" if
294      *            this is set to MINUTE_IN_MILLIS. Pass one of 0,
295      *            MINUTE_IN_MILLIS, HOUR_IN_MILLIS, DAY_IN_MILLIS,
296      *            WEEK_IN_MILLIS
297      * @param flags a bit mask of formatting options, such as
298      *            {@link #FORMAT_NUMERIC_DATE} or
299      *            {@link #FORMAT_ABBREV_RELATIVE}
300      */
getRelativeTimeSpanString(long time, long now, long minResolution, int flags)301     public static CharSequence getRelativeTimeSpanString(long time, long now, long minResolution,
302             int flags) {
303         return RelativeDateTimeFormatter.getRelativeTimeSpanString(Locale.getDefault(),
304                 TimeZone.getDefault(), time, now, minResolution, flags);
305     }
306 
307     /**
308      * Return string describing the elapsed time since startTime formatted like
309      * "[relative time/date], [time]".
310      * <p>
311      * Example output strings for the US date format.
312      * <ul>
313      * <li>3 min. ago, 10:15 AM</li>
314      * <li>Yesterday, 12:20 PM</li>
315      * <li>Dec 12, 4:12 AM</li>
316      * <li>11/14/2007, 8:20 AM</li>
317      * </ul>
318      *
319      * @param time some time in the past.
320      * @param minResolution the minimum elapsed time (in milliseconds) to report
321      *            when showing relative times. For example, a time 3 seconds in
322      *            the past will be reported as "0 minutes ago" if this is set to
323      *            {@link #MINUTE_IN_MILLIS}.
324      * @param transitionResolution the elapsed time (in milliseconds) at which
325      *            to stop reporting relative measurements. Elapsed times greater
326      *            than this resolution will default to normal date formatting.
327      *            For example, will transition from "7 days ago" to "Dec 12"
328      *            when using {@link #WEEK_IN_MILLIS}.
329      */
getRelativeDateTimeString(Context c, long time, long minResolution, long transitionResolution, int flags)330     public static CharSequence getRelativeDateTimeString(Context c, long time, long minResolution,
331             long transitionResolution, int flags) {
332         // Same reason as in formatDateRange() to explicitly indicate 12- or 24-hour format.
333         if ((flags & (FORMAT_SHOW_TIME | FORMAT_12HOUR | FORMAT_24HOUR)) == FORMAT_SHOW_TIME) {
334             flags |= DateFormat.is24HourFormat(c) ? FORMAT_24HOUR : FORMAT_12HOUR;
335         }
336 
337         return RelativeDateTimeFormatter.getRelativeDateTimeString(Locale.getDefault(),
338                 TimeZone.getDefault(), time, System.currentTimeMillis(), minResolution,
339                 transitionResolution, flags);
340     }
341 
initFormatStrings()342     private static void initFormatStrings() {
343         synchronized (sLock) {
344             initFormatStringsLocked();
345         }
346     }
347 
initFormatStringsLocked()348     private static void initFormatStringsLocked() {
349         Resources r = Resources.getSystem();
350         Configuration cfg = r.getConfiguration();
351         if (sLastConfig == null || !sLastConfig.equals(cfg)) {
352             sLastConfig = cfg;
353             sElapsedFormatMMSS = r.getString(com.android.internal.R.string.elapsed_time_short_format_mm_ss);
354             sElapsedFormatHMMSS = r.getString(com.android.internal.R.string.elapsed_time_short_format_h_mm_ss);
355         }
356     }
357 
358     /**
359      * Returns the given duration in a human-friendly format. For example,
360      * "4 minutes" or "1 second". Returns only the largest meaningful unit of time,
361      * from seconds up to hours.
362      *
363      * @hide
364      */
365     @UnsupportedAppUsage
formatDuration(long millis)366     public static CharSequence formatDuration(long millis) {
367         return formatDuration(millis, LENGTH_LONG);
368     }
369 
370     /**
371      * Returns the given duration in a human-friendly format. For example,
372      * "4 minutes" or "1 second". Returns only the largest meaningful unit of time,
373      * from seconds up to hours.
374      * <p>
375      * You can use abbrev to specify a preference for abbreviations (but note that some
376      * locales may not have abbreviations). Use LENGTH_LONG for the full spelling (e.g. "2 hours"),
377      * LENGTH_SHORT for the abbreviated spelling if available (e.g. "2 hr"), and LENGTH_SHORTEST for
378      * the briefest form available (e.g. "2h").
379      * @hide
380      */
381     @UnsupportedAppUsage
formatDuration(long millis, int abbrev)382     public static CharSequence formatDuration(long millis, int abbrev) {
383         final FormatWidth width;
384         switch (abbrev) {
385             case LENGTH_LONG:
386                 width = FormatWidth.WIDE;
387                 break;
388             case LENGTH_SHORT:
389             case LENGTH_SHORTER:
390             case LENGTH_MEDIUM:
391                 width = FormatWidth.SHORT;
392                 break;
393             case LENGTH_SHORTEST:
394                 width = FormatWidth.NARROW;
395                 break;
396             default:
397                 width = FormatWidth.WIDE;
398         }
399         final MeasureFormat formatter = MeasureFormat.getInstance(Locale.getDefault(), width);
400         if (millis >= HOUR_IN_MILLIS) {
401             final int hours = (int) ((millis + 1800000) / HOUR_IN_MILLIS);
402             return formatter.format(new Measure(hours, MeasureUnit.HOUR));
403         } else if (millis >= MINUTE_IN_MILLIS) {
404             final int minutes = (int) ((millis + 30000) / MINUTE_IN_MILLIS);
405             return formatter.format(new Measure(minutes, MeasureUnit.MINUTE));
406         } else {
407             final int seconds = (int) ((millis + 500) / SECOND_IN_MILLIS);
408             return formatter.format(new Measure(seconds, MeasureUnit.SECOND));
409         }
410     }
411 
412     /**
413      * Formats an elapsed time in the form "MM:SS" or "H:MM:SS"
414      * for display on the call-in-progress screen.
415      * @param elapsedSeconds the elapsed time in seconds.
416      */
formatElapsedTime(long elapsedSeconds)417     public static String formatElapsedTime(long elapsedSeconds) {
418         return formatElapsedTime(null, elapsedSeconds);
419     }
420 
421     /**
422      * Formats an elapsed time in a format like "MM:SS" or "H:MM:SS" (using a form
423      * suited to the current locale), similar to that used on the call-in-progress
424      * screen.
425      *
426      * @param recycle {@link StringBuilder} to recycle, or null to use a temporary one.
427      * @param elapsedSeconds the elapsed time in seconds.
428      */
formatElapsedTime(StringBuilder recycle, long elapsedSeconds)429     public static String formatElapsedTime(StringBuilder recycle, long elapsedSeconds) {
430         // Break the elapsed seconds into hours, minutes, and seconds.
431         long hours = 0;
432         long minutes = 0;
433         long seconds = 0;
434         if (elapsedSeconds >= 3600) {
435             hours = elapsedSeconds / 3600;
436             elapsedSeconds -= hours * 3600;
437         }
438         if (elapsedSeconds >= 60) {
439             minutes = elapsedSeconds / 60;
440             elapsedSeconds -= minutes * 60;
441         }
442         seconds = elapsedSeconds;
443 
444         // Create a StringBuilder if we weren't given one to recycle.
445         // TODO: if we cared, we could have a thread-local temporary StringBuilder.
446         StringBuilder sb = recycle;
447         if (sb == null) {
448             sb = new StringBuilder(8);
449         } else {
450             sb.setLength(0);
451         }
452 
453         // Format the broken-down time in a locale-appropriate way.
454         // TODO: use icu4c when http://unicode.org/cldr/trac/ticket/3407 is fixed.
455         Formatter f = new Formatter(sb, Locale.getDefault());
456         initFormatStrings();
457         if (hours > 0) {
458             return f.format(sElapsedFormatHMMSS, hours, minutes, seconds).toString();
459         } else {
460             return f.format(sElapsedFormatMMSS, minutes, seconds).toString();
461         }
462     }
463 
464     /**
465      * Format a date / time such that if the then is on the same day as now, it shows
466      * just the time and if it's a different day, it shows just the date.
467      *
468      * <p>The parameters dateFormat and timeFormat should each be one of
469      * {@link java.text.DateFormat#DEFAULT},
470      * {@link java.text.DateFormat#FULL},
471      * {@link java.text.DateFormat#LONG},
472      * {@link java.text.DateFormat#MEDIUM}
473      * or
474      * {@link java.text.DateFormat#SHORT}
475      *
476      * @param then the date to format
477      * @param now the base time
478      * @param dateStyle how to format the date portion.
479      * @param timeStyle how to format the time portion.
480      */
formatSameDayTime(long then, long now, int dateStyle, int timeStyle)481     public static final CharSequence formatSameDayTime(long then, long now,
482             int dateStyle, int timeStyle) {
483         Calendar thenCal = new GregorianCalendar();
484         thenCal.setTimeInMillis(then);
485         Date thenDate = thenCal.getTime();
486         Calendar nowCal = new GregorianCalendar();
487         nowCal.setTimeInMillis(now);
488 
489         java.text.DateFormat f;
490 
491         if (thenCal.get(Calendar.YEAR) == nowCal.get(Calendar.YEAR)
492                 && thenCal.get(Calendar.MONTH) == nowCal.get(Calendar.MONTH)
493                 && thenCal.get(Calendar.DAY_OF_MONTH) == nowCal.get(Calendar.DAY_OF_MONTH)) {
494             f = java.text.DateFormat.getTimeInstance(timeStyle);
495         } else {
496             f = java.text.DateFormat.getDateInstance(dateStyle);
497         }
498         return f.format(thenDate);
499     }
500 
501     /**
502      * @return true if the supplied when is today else false
503      */
isToday(long when)504     public static boolean isToday(long when) {
505         Time time = new Time();
506         time.set(when);
507 
508         int thenYear = time.year;
509         int thenMonth = time.month;
510         int thenMonthDay = time.monthDay;
511 
512         time.set(System.currentTimeMillis());
513         return (thenYear == time.year)
514                 && (thenMonth == time.month)
515                 && (thenMonthDay == time.monthDay);
516     }
517 
518     /**
519      * Formats a date or a time range according to the local conventions.
520      * <p>
521      * Note that this is a convenience method. Using it involves creating an
522      * internal {@link java.util.Formatter} instance on-the-fly, which is
523      * somewhat costly in terms of memory and time. This is probably acceptable
524      * if you use the method only rarely, but if you rely on it for formatting a
525      * large number of dates, consider creating and reusing your own
526      * {@link java.util.Formatter} instance and use the version of
527      * {@link #formatDateRange(Context, long, long, int) formatDateRange}
528      * that takes a {@link java.util.Formatter}.
529      *
530      * @param context the context is required only if the time is shown
531      * @param startMillis the start time in UTC milliseconds
532      * @param endMillis the end time in UTC milliseconds
533      * @param flags a bit mask of options See
534      * {@link #formatDateRange(Context, Formatter, long, long, int, String) formatDateRange}
535      * @return a string containing the formatted date/time range.
536      */
formatDateRange(Context context, long startMillis, long endMillis, int flags)537     public static String formatDateRange(Context context, long startMillis,
538             long endMillis, int flags) {
539         Formatter f = new Formatter(new StringBuilder(50), Locale.getDefault());
540         return formatDateRange(context, f, startMillis, endMillis, flags).toString();
541     }
542 
543     /**
544      * Formats a date or a time range according to the local conventions.
545      * <p>
546      * Note that this is a convenience method for formatting the date or
547      * time range in the local time zone. If you want to specify the time
548      * zone please use
549      * {@link #formatDateRange(Context, Formatter, long, long, int, String) formatDateRange}.
550      *
551      * @param context the context is required only if the time is shown
552      * @param formatter the Formatter used for formatting the date range.
553      * Note: be sure to call setLength(0) on StringBuilder passed to
554      * the Formatter constructor unless you want the results to accumulate.
555      * @param startMillis the start time in UTC milliseconds
556      * @param endMillis the end time in UTC milliseconds
557      * @param flags a bit mask of options See
558      * {@link #formatDateRange(Context, Formatter, long, long, int, String) formatDateRange}
559      * @return a string containing the formatted date/time range.
560      */
formatDateRange(Context context, Formatter formatter, long startMillis, long endMillis, int flags)561     public static Formatter formatDateRange(Context context, Formatter formatter, long startMillis,
562             long endMillis, int flags) {
563         return formatDateRange(context, formatter, startMillis, endMillis, flags, null);
564     }
565 
566     /**
567      * Formats a date or a time range according to the local conventions.
568      *
569      * <p>
570      * Example output strings (date formats in these examples are shown using
571      * the US date format convention but that may change depending on the
572      * local settings):
573      * <ul>
574      *   <li>10:15am</li>
575      *   <li>3:00pm - 4:00pm</li>
576      *   <li>3pm - 4pm</li>
577      *   <li>3PM - 4PM</li>
578      *   <li>08:00 - 17:00</li>
579      *   <li>Oct 9</li>
580      *   <li>Tue, Oct 9</li>
581      *   <li>October 9, 2007</li>
582      *   <li>Oct 9 - 10</li>
583      *   <li>Oct 9 - 10, 2007</li>
584      *   <li>Oct 28 - Nov 3, 2007</li>
585      *   <li>Dec 31, 2007 - Jan 1, 2008</li>
586      *   <li>Oct 9, 8:00am - Oct 10, 5:00pm</li>
587      *   <li>12/31/2007 - 01/01/2008</li>
588      * </ul>
589      *
590      * <p>
591      * The flags argument is a bitmask of options from the following list:
592      *
593      * <ul>
594      *   <li>FORMAT_SHOW_TIME</li>
595      *   <li>FORMAT_SHOW_WEEKDAY</li>
596      *   <li>FORMAT_SHOW_YEAR</li>
597      *   <li>FORMAT_SHOW_DATE</li>
598      *   <li>FORMAT_NO_MONTH_DAY</li>
599      *   <li>FORMAT_12HOUR</li>
600      *   <li>FORMAT_24HOUR</li>
601      *   <li>FORMAT_CAP_AMPM</li>
602      *   <li>FORMAT_NO_NOON</li>
603      *   <li>FORMAT_CAP_NOON</li>
604      *   <li>FORMAT_NO_MIDNIGHT</li>
605      *   <li>FORMAT_CAP_MIDNIGHT</li>
606      *   <li>FORMAT_UTC</li>
607      *   <li>FORMAT_ABBREV_TIME</li>
608      *   <li>FORMAT_ABBREV_WEEKDAY</li>
609      *   <li>FORMAT_ABBREV_MONTH</li>
610      *   <li>FORMAT_ABBREV_ALL</li>
611      *   <li>FORMAT_NUMERIC_DATE</li>
612      * </ul>
613      *
614      * <p>
615      * If FORMAT_SHOW_TIME is set, the time is shown as part of the date range.
616      * If the start and end time are the same, then just the start time is
617      * shown.
618      *
619      * <p>
620      * If FORMAT_SHOW_WEEKDAY is set, then the weekday is shown.
621      *
622      * <p>
623      * If FORMAT_SHOW_YEAR is set, then the year is always shown.
624      * If FORMAT_SHOW_YEAR is not set, then the year
625      * is shown only if it is different from the current year, or if the start
626      * and end dates fall on different years.
627      *
628      * <p>
629      * Normally the date is shown unless the start and end day are the same.
630      * If FORMAT_SHOW_DATE is set, then the date is always shown, even for
631      * same day ranges.
632      *
633      * <p>
634      * If FORMAT_NO_MONTH_DAY is set, then if the date is shown, just the
635      * month name will be shown, not the day of the month.  For example,
636      * "January, 2008" instead of "January 6 - 12, 2008".
637      *
638      * <p>
639      * If FORMAT_CAP_AMPM is set and 12-hour time is used, then the "AM"
640      * and "PM" are capitalized.  You should not use this flag
641      * because in some locales these terms cannot be capitalized, and in
642      * many others it doesn't make sense to do so even though it is possible.
643      *
644      * <p>
645      * If FORMAT_NO_NOON is set and 12-hour time is used, then "12pm" is
646      * shown instead of "noon".
647      *
648      * <p>
649      * If FORMAT_CAP_NOON is set and 12-hour time is used, then "Noon" is
650      * shown instead of "noon".  You should probably not use this flag
651      * because in many locales it will not make sense to capitalize
652      * the term.
653      *
654      * <p>
655      * If FORMAT_NO_MIDNIGHT is set and 12-hour time is used, then "12am" is
656      * shown instead of "midnight".
657      *
658      * <p>
659      * If FORMAT_CAP_MIDNIGHT is set and 12-hour time is used, then "Midnight"
660      * is shown instead of "midnight".  You should probably not use this
661      * flag because in many locales it will not make sense to capitalize
662      * the term.
663      *
664      * <p>
665      * If FORMAT_12HOUR is set and the time is shown, then the time is
666      * shown in the 12-hour time format. You should not normally set this.
667      * Instead, let the time format be chosen automatically according to the
668      * system settings. If both FORMAT_12HOUR and FORMAT_24HOUR are set, then
669      * FORMAT_24HOUR takes precedence.
670      *
671      * <p>
672      * If FORMAT_24HOUR is set and the time is shown, then the time is
673      * shown in the 24-hour time format. You should not normally set this.
674      * Instead, let the time format be chosen automatically according to the
675      * system settings. If both FORMAT_12HOUR and FORMAT_24HOUR are set, then
676      * FORMAT_24HOUR takes precedence.
677      *
678      * <p>
679      * If FORMAT_UTC is set, then the UTC time zone is used for the start
680      * and end milliseconds unless a time zone is specified. If a time zone
681      * is specified it will be used regardless of the FORMAT_UTC flag.
682      *
683      * <p>
684      * If FORMAT_ABBREV_TIME is set and 12-hour time format is used, then the
685      * start and end times (if shown) are abbreviated by not showing the minutes
686      * if they are zero.  For example, instead of "3:00pm" the time would be
687      * abbreviated to "3pm".
688      *
689      * <p>
690      * If FORMAT_ABBREV_WEEKDAY is set, then the weekday (if shown) is
691      * abbreviated to a 3-letter string.
692      *
693      * <p>
694      * If FORMAT_ABBREV_MONTH is set, then the month (if shown) is abbreviated
695      * to a 3-letter string.
696      *
697      * <p>
698      * If FORMAT_ABBREV_ALL is set, then the weekday and the month (if shown)
699      * are abbreviated to 3-letter strings.
700      *
701      * <p>
702      * If FORMAT_NUMERIC_DATE is set, then the date is shown in numeric format
703      * instead of using the name of the month.  For example, "12/31/2008"
704      * instead of "December 31, 2008".
705      *
706      * <p>
707      * If the end date ends at 12:00am at the beginning of a day, it is
708      * formatted as the end of the previous day in two scenarios:
709      * <ul>
710      *   <li>For single day events. This results in "8pm - midnight" instead of
711      *       "Nov 10, 8pm - Nov 11, 12am".</li>
712      *   <li>When the time is not displayed. This results in "Nov 10 - 11" for
713      *       an event with a start date of Nov 10 and an end date of Nov 12 at
714      *       00:00.</li>
715      * </ul>
716      *
717      * @param context the context is required only if the time is shown
718      * @param formatter the Formatter used for formatting the date range.
719      * Note: be sure to call setLength(0) on StringBuilder passed to
720      * the Formatter constructor unless you want the results to accumulate.
721      * @param startMillis the start time in UTC milliseconds
722      * @param endMillis the end time in UTC milliseconds
723      * @param flags a bit mask of options
724      * @param timeZone the time zone to compute the string in. Use null for local
725      * or if the FORMAT_UTC flag is being used.
726      *
727      * @return the formatter with the formatted date/time range appended to the string buffer.
728      */
formatDateRange(Context context, Formatter formatter, long startMillis, long endMillis, int flags, String timeZone)729     public static Formatter formatDateRange(Context context, Formatter formatter, long startMillis,
730                                             long endMillis, int flags, String timeZone) {
731         // If we're being asked to format a time without being explicitly told whether to use
732         // the 12- or 24-hour clock, icu4c will fall back to the locale's preferred 12/24 format,
733         // but we want to fall back to the user's preference.
734         if ((flags & (FORMAT_SHOW_TIME | FORMAT_12HOUR | FORMAT_24HOUR)) == FORMAT_SHOW_TIME) {
735             flags |= DateFormat.is24HourFormat(context) ? FORMAT_24HOUR : FORMAT_12HOUR;
736         }
737 
738         String range = DateIntervalFormat.formatDateRange(startMillis, endMillis, flags, timeZone);
739         try {
740             formatter.out().append(range);
741         } catch (IOException impossible) {
742             throw new AssertionError(impossible);
743         }
744         return formatter;
745     }
746 
747     /**
748      * Formats a date or a time according to the local conventions. There are
749      * lots of options that allow the caller to control, for example, if the
750      * time is shown, if the day of the week is shown, if the month name is
751      * abbreviated, if noon is shown instead of 12pm, and so on. For the
752      * complete list of options, see the documentation for
753      * {@link #formatDateRange}.
754      * <p>
755      * Example output strings (date formats in these examples are shown using
756      * the US date format convention but that may change depending on the
757      * local settings):
758      * <ul>
759      *   <li>10:15am</li>
760      *   <li>3:00pm</li>
761      *   <li>3pm</li>
762      *   <li>3PM</li>
763      *   <li>08:00</li>
764      *   <li>17:00</li>
765      *   <li>noon</li>
766      *   <li>Noon</li>
767      *   <li>midnight</li>
768      *   <li>Midnight</li>
769      *   <li>Oct 31</li>
770      *   <li>Oct 31, 2007</li>
771      *   <li>October 31, 2007</li>
772      *   <li>10am, Oct 31</li>
773      *   <li>17:00, Oct 31</li>
774      *   <li>Wed</li>
775      *   <li>Wednesday</li>
776      *   <li>10am, Wed, Oct 31</li>
777      *   <li>Wed, Oct 31</li>
778      *   <li>Wednesday, Oct 31</li>
779      *   <li>Wed, Oct 31, 2007</li>
780      *   <li>Wed, October 31</li>
781      *   <li>10/31/2007</li>
782      * </ul>
783      *
784      * @param context the context is required only if the time is shown
785      * @param millis a point in time in UTC milliseconds
786      * @param flags a bit mask of formatting options
787      * @return a string containing the formatted date/time.
788      */
formatDateTime(Context context, long millis, int flags)789     public static String formatDateTime(Context context, long millis, int flags) {
790         return formatDateRange(context, millis, millis, flags);
791     }
792 
793     /**
794      * @return a relative time string to display the time expressed by millis.  Times
795      * are counted starting at midnight, which means that assuming that the current
796      * time is March 31st, 0:30:
797      * <ul>
798      *   <li>"millis=0:10 today" will be displayed as "0:10"</li>
799      *   <li>"millis=11:30pm the day before" will be displayed as "Mar 30"</li>
800      * </ul>
801      * If the given millis is in a different year, then the full date is
802      * returned in numeric format (e.g., "10/12/2008").
803      *
804      * @param withPreposition If true, the string returned will include the correct
805      * preposition ("at 9:20am", "on 10/12/2008" or "on May 29").
806      */
getRelativeTimeSpanString(Context c, long millis, boolean withPreposition)807     public static CharSequence getRelativeTimeSpanString(Context c, long millis,
808             boolean withPreposition) {
809 
810         String result;
811         long now = System.currentTimeMillis();
812         long span = Math.abs(now - millis);
813 
814         synchronized (DateUtils.class) {
815             if (sNowTime == null) {
816                 sNowTime = new Time();
817             }
818 
819             if (sThenTime == null) {
820                 sThenTime = new Time();
821             }
822 
823             sNowTime.set(now);
824             sThenTime.set(millis);
825 
826             int prepositionId;
827             if (span < DAY_IN_MILLIS && sNowTime.weekDay == sThenTime.weekDay) {
828                 // Same day
829                 int flags = FORMAT_SHOW_TIME;
830                 result = formatDateRange(c, millis, millis, flags);
831                 prepositionId = R.string.preposition_for_time;
832             } else if (sNowTime.year != sThenTime.year) {
833                 // Different years
834                 int flags = FORMAT_SHOW_DATE | FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE;
835                 result = formatDateRange(c, millis, millis, flags);
836 
837                 // This is a date (like "10/31/2008" so use the date preposition)
838                 prepositionId = R.string.preposition_for_date;
839             } else {
840                 // Default
841                 int flags = FORMAT_SHOW_DATE | FORMAT_ABBREV_MONTH;
842                 result = formatDateRange(c, millis, millis, flags);
843                 prepositionId = R.string.preposition_for_date;
844             }
845             if (withPreposition) {
846                 Resources res = c.getResources();
847                 result = res.getString(prepositionId, result);
848             }
849         }
850         return result;
851     }
852 
853     /**
854      * Convenience function to return relative time string without preposition.
855      * @param c context for resources
856      * @param millis time in milliseconds
857      * @return {@link CharSequence} containing relative time.
858      * @see #getRelativeTimeSpanString(Context, long, boolean)
859      */
getRelativeTimeSpanString(Context c, long millis)860     public static CharSequence getRelativeTimeSpanString(Context c, long millis) {
861         return getRelativeTimeSpanString(c, millis, false /* no preposition */);
862     }
863 
864     private static Time sNowTime;
865     private static Time sThenTime;
866 }
867