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