/* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.text.format; import com.android.internal.R; import android.content.Context; import android.content.res.Configuration; import android.content.res.Resources; import java.io.IOException; import java.util.Calendar; import java.util.Date; import java.util.Formatter; import java.util.GregorianCalendar; import java.util.Locale; import java.util.TimeZone; import libcore.icu.DateIntervalFormat; import libcore.icu.LocaleData; import libcore.icu.RelativeDateTimeFormatter; /** * This class contains various date-related utilities for creating text for things like * elapsed time and date ranges, strings for days of the week and months, and AM/PM text etc. */ public class DateUtils { private static final Object sLock = new Object(); private static Configuration sLastConfig; private static String sElapsedFormatMMSS; private static String sElapsedFormatHMMSS; public static final long SECOND_IN_MILLIS = 1000; public static final long MINUTE_IN_MILLIS = SECOND_IN_MILLIS * 60; public static final long HOUR_IN_MILLIS = MINUTE_IN_MILLIS * 60; public static final long DAY_IN_MILLIS = HOUR_IN_MILLIS * 24; public static final long WEEK_IN_MILLIS = DAY_IN_MILLIS * 7; /** * This constant is actually the length of 364 days, not of a year! */ public static final long YEAR_IN_MILLIS = WEEK_IN_MILLIS * 52; // The following FORMAT_* symbols are used for specifying the format of // dates and times in the formatDateRange method. public static final int FORMAT_SHOW_TIME = 0x00001; public static final int FORMAT_SHOW_WEEKDAY = 0x00002; public static final int FORMAT_SHOW_YEAR = 0x00004; public static final int FORMAT_NO_YEAR = 0x00008; public static final int FORMAT_SHOW_DATE = 0x00010; public static final int FORMAT_NO_MONTH_DAY = 0x00020; @Deprecated public static final int FORMAT_12HOUR = 0x00040; @Deprecated public static final int FORMAT_24HOUR = 0x00080; @Deprecated public static final int FORMAT_CAP_AMPM = 0x00100; public static final int FORMAT_NO_NOON = 0x00200; @Deprecated public static final int FORMAT_CAP_NOON = 0x00400; public static final int FORMAT_NO_MIDNIGHT = 0x00800; @Deprecated public static final int FORMAT_CAP_MIDNIGHT = 0x01000; /** * @deprecated Use * {@link #formatDateRange(Context, Formatter, long, long, int, String) formatDateRange} * and pass in {@link Time#TIMEZONE_UTC Time.TIMEZONE_UTC} for the timeZone instead. */ @Deprecated public static final int FORMAT_UTC = 0x02000; public static final int FORMAT_ABBREV_TIME = 0x04000; public static final int FORMAT_ABBREV_WEEKDAY = 0x08000; public static final int FORMAT_ABBREV_MONTH = 0x10000; public static final int FORMAT_NUMERIC_DATE = 0x20000; public static final int FORMAT_ABBREV_RELATIVE = 0x40000; public static final int FORMAT_ABBREV_ALL = 0x80000; @Deprecated public static final int FORMAT_CAP_NOON_MIDNIGHT = (FORMAT_CAP_NOON | FORMAT_CAP_MIDNIGHT); @Deprecated public static final int FORMAT_NO_NOON_MIDNIGHT = (FORMAT_NO_NOON | FORMAT_NO_MIDNIGHT); // Date and time format strings that are constant and don't need to be // translated. /** * This is not actually the preferred 24-hour date format in all locales. * @deprecated Use {@link java.text.SimpleDateFormat} instead. */ @Deprecated public static final String HOUR_MINUTE_24 = "%H:%M"; public static final String MONTH_FORMAT = "%B"; /** * This is not actually a useful month name in all locales. * @deprecated Use {@link java.text.SimpleDateFormat} instead. */ @Deprecated public static final String ABBREV_MONTH_FORMAT = "%b"; public static final String NUMERIC_MONTH_FORMAT = "%m"; public static final String MONTH_DAY_FORMAT = "%-d"; public static final String YEAR_FORMAT = "%Y"; public static final String YEAR_FORMAT_TWO_DIGITS = "%g"; public static final String WEEKDAY_FORMAT = "%A"; public static final String ABBREV_WEEKDAY_FORMAT = "%a"; /** @deprecated Do not use. */ public static final int[] sameYearTable = null; /** @deprecated Do not use. */ public static final int[] sameMonthTable = null; /** * Request the full spelled-out name. For use with the 'abbrev' parameter of * {@link #getDayOfWeekString} and {@link #getMonthString}. * * @more
* e.g. "Sunday" or "January" * @deprecated Use {@link java.text.SimpleDateFormat} instead. */ @Deprecated public static final int LENGTH_LONG = 10; /** * Request an abbreviated version of the name. For use with the 'abbrev' * parameter of {@link #getDayOfWeekString} and {@link #getMonthString}. * * @more
* e.g. "Sun" or "Jan" * @deprecated Use {@link java.text.SimpleDateFormat} instead. */ @Deprecated public static final int LENGTH_MEDIUM = 20; /** * Request a shorter abbreviated version of the name. * For use with the 'abbrev' parameter of {@link #getDayOfWeekString} and {@link #getMonthString}. * @more *
e.g. "Su" or "Jan" *
In most languages, the results returned for LENGTH_SHORT will be the same as * the results returned for {@link #LENGTH_MEDIUM}. * @deprecated Use {@link java.text.SimpleDateFormat} instead. */ @Deprecated public static final int LENGTH_SHORT = 30; /** * Request an even shorter abbreviated version of the name. * Do not use this. Currently this will always return the same result * as {@link #LENGTH_SHORT}. * @deprecated Use {@link java.text.SimpleDateFormat} instead. */ @Deprecated public static final int LENGTH_SHORTER = 40; /** * Request an even shorter abbreviated version of the name. * For use with the 'abbrev' parameter of {@link #getDayOfWeekString} and {@link #getMonthString}. * @more *
e.g. "S", "T", "T" or "J" *
In some languages, the results returned for LENGTH_SHORTEST will be the same as * the results returned for {@link #LENGTH_SHORT}. * @deprecated Use {@link java.text.SimpleDateFormat} instead. */ @Deprecated public static final int LENGTH_SHORTEST = 50; /** * Return a string for the day of the week. * @param dayOfWeek One of {@link Calendar#SUNDAY Calendar.SUNDAY}, * {@link Calendar#MONDAY Calendar.MONDAY}, etc. * @param abbrev One of {@link #LENGTH_LONG}, {@link #LENGTH_SHORT}, * {@link #LENGTH_MEDIUM}, or {@link #LENGTH_SHORTEST}. * Note that in most languages, {@link #LENGTH_SHORT} * will return the same as {@link #LENGTH_MEDIUM}. * Undefined lengths will return {@link #LENGTH_MEDIUM} * but may return something different in the future. * @throws IndexOutOfBoundsException if the dayOfWeek is out of bounds. * @deprecated Use {@link java.text.SimpleDateFormat} instead. */ @Deprecated public static String getDayOfWeekString(int dayOfWeek, int abbrev) { LocaleData d = LocaleData.get(Locale.getDefault()); String[] names; switch (abbrev) { case LENGTH_LONG: names = d.longWeekdayNames; break; case LENGTH_MEDIUM: names = d.shortWeekdayNames; break; case LENGTH_SHORT: names = d.shortWeekdayNames; break; // TODO case LENGTH_SHORTER: names = d.shortWeekdayNames; break; // TODO case LENGTH_SHORTEST: names = d.tinyWeekdayNames; break; default: names = d.shortWeekdayNames; break; } return names[dayOfWeek]; } /** * Return a localized string for AM or PM. * @param ampm Either {@link Calendar#AM Calendar.AM} or {@link Calendar#PM Calendar.PM}. * @throws IndexOutOfBoundsException if the ampm is out of bounds. * @return Localized version of "AM" or "PM". * @deprecated Use {@link java.text.SimpleDateFormat} instead. */ @Deprecated public static String getAMPMString(int ampm) { return LocaleData.get(Locale.getDefault()).amPm[ampm - Calendar.AM]; } /** * Return a localized string for the month of the year. * @param month One of {@link Calendar#JANUARY Calendar.JANUARY}, * {@link Calendar#FEBRUARY Calendar.FEBRUARY}, etc. * @param abbrev One of {@link #LENGTH_LONG}, {@link #LENGTH_MEDIUM}, * or {@link #LENGTH_SHORTEST}. * Undefined lengths will return {@link #LENGTH_MEDIUM} * but may return something different in the future. * @return Localized month of the year. * @deprecated Use {@link java.text.SimpleDateFormat} instead. */ @Deprecated public static String getMonthString(int month, int abbrev) { LocaleData d = LocaleData.get(Locale.getDefault()); String[] names; switch (abbrev) { case LENGTH_LONG: names = d.longMonthNames; break; case LENGTH_MEDIUM: names = d.shortMonthNames; break; case LENGTH_SHORT: names = d.shortMonthNames; break; case LENGTH_SHORTER: names = d.shortMonthNames; break; case LENGTH_SHORTEST: names = d.tinyMonthNames; break; default: names = d.shortMonthNames; break; } return names[month]; } /** * Returns a string describing the elapsed time since startTime. *
* The minimum timespan to report is set to {@link #MINUTE_IN_MILLIS}. * @param startTime some time in the past. * @return a String object containing the elapsed time. * @see #getRelativeTimeSpanString(long, long, long) */ public static CharSequence getRelativeTimeSpanString(long startTime) { return getRelativeTimeSpanString(startTime, System.currentTimeMillis(), MINUTE_IN_MILLIS); } /** * Returns a string describing 'time' as a time relative to 'now'. *
* Time spans in the past are formatted like "42 minutes ago". * Time spans in the future are formatted like "In 42 minutes". * * @param time the time to describe, in milliseconds * @param now the current time in milliseconds * @param minResolution the minimum timespan to report. For example, a time 3 seconds in the * past will be reported as "0 minutes ago" if this is set to MINUTE_IN_MILLIS. Pass one of * 0, MINUTE_IN_MILLIS, HOUR_IN_MILLIS, DAY_IN_MILLIS, WEEK_IN_MILLIS */ public static CharSequence getRelativeTimeSpanString(long time, long now, long minResolution) { int flags = FORMAT_SHOW_DATE | FORMAT_SHOW_YEAR | FORMAT_ABBREV_MONTH; return getRelativeTimeSpanString(time, now, minResolution, flags); } /** * Returns a string describing 'time' as a time relative to 'now'. *
* Time spans in the past are formatted like "42 minutes ago". Time spans in * the future are formatted like "In 42 minutes". *
* Can use {@link #FORMAT_ABBREV_RELATIVE} flag to use abbreviated relative * times, like "42 mins ago". * * @param time the time to describe, in milliseconds * @param now the current time in milliseconds * @param minResolution the minimum timespan to report. For example, a time * 3 seconds in the past will be reported as "0 minutes ago" if * this is set to MINUTE_IN_MILLIS. Pass one of 0, * MINUTE_IN_MILLIS, HOUR_IN_MILLIS, DAY_IN_MILLIS, * WEEK_IN_MILLIS * @param flags a bit mask of formatting options, such as * {@link #FORMAT_NUMERIC_DATE} or * {@link #FORMAT_ABBREV_RELATIVE} */ public static CharSequence getRelativeTimeSpanString(long time, long now, long minResolution, int flags) { return RelativeDateTimeFormatter.getRelativeTimeSpanString(Locale.getDefault(), TimeZone.getDefault(), time, now, minResolution, flags); } /** * Return string describing the elapsed time since startTime formatted like * "[relative time/date], [time]". *
* Example output strings for the US date format. *
The parameters dateFormat and timeFormat should each be one of * {@link java.text.DateFormat#DEFAULT}, * {@link java.text.DateFormat#FULL}, * {@link java.text.DateFormat#LONG}, * {@link java.text.DateFormat#MEDIUM} * or * {@link java.text.DateFormat#SHORT} * * @param then the date to format * @param now the base time * @param dateStyle how to format the date portion. * @param timeStyle how to format the time portion. */ public static final CharSequence formatSameDayTime(long then, long now, int dateStyle, int timeStyle) { Calendar thenCal = new GregorianCalendar(); thenCal.setTimeInMillis(then); Date thenDate = thenCal.getTime(); Calendar nowCal = new GregorianCalendar(); nowCal.setTimeInMillis(now); java.text.DateFormat f; if (thenCal.get(Calendar.YEAR) == nowCal.get(Calendar.YEAR) && thenCal.get(Calendar.MONTH) == nowCal.get(Calendar.MONTH) && thenCal.get(Calendar.DAY_OF_MONTH) == nowCal.get(Calendar.DAY_OF_MONTH)) { f = java.text.DateFormat.getTimeInstance(timeStyle); } else { f = java.text.DateFormat.getDateInstance(dateStyle); } return f.format(thenDate); } /** * @return true if the supplied when is today else false */ public static boolean isToday(long when) { Time time = new Time(); time.set(when); int thenYear = time.year; int thenMonth = time.month; int thenMonthDay = time.monthDay; time.set(System.currentTimeMillis()); return (thenYear == time.year) && (thenMonth == time.month) && (thenMonthDay == time.monthDay); } /** * Formats a date or a time range according to the local conventions. *
* Note that this is a convenience method. Using it involves creating an * internal {@link java.util.Formatter} instance on-the-fly, which is * somewhat costly in terms of memory and time. This is probably acceptable * if you use the method only rarely, but if you rely on it for formatting a * large number of dates, consider creating and reusing your own * {@link java.util.Formatter} instance and use the version of * {@link #formatDateRange(Context, long, long, int) formatDateRange} * that takes a {@link java.util.Formatter}. * * @param context the context is required only if the time is shown * @param startMillis the start time in UTC milliseconds * @param endMillis the end time in UTC milliseconds * @param flags a bit mask of options See * {@link #formatDateRange(Context, Formatter, long, long, int, String) formatDateRange} * @return a string containing the formatted date/time range. */ public static String formatDateRange(Context context, long startMillis, long endMillis, int flags) { Formatter f = new Formatter(new StringBuilder(50), Locale.getDefault()); return formatDateRange(context, f, startMillis, endMillis, flags).toString(); } /** * Formats a date or a time range according to the local conventions. *
* Note that this is a convenience method for formatting the date or * time range in the local time zone. If you want to specify the time * zone please use * {@link #formatDateRange(Context, Formatter, long, long, int, String) formatDateRange}. * * @param context the context is required only if the time is shown * @param formatter the Formatter used for formatting the date range. * Note: be sure to call setLength(0) on StringBuilder passed to * the Formatter constructor unless you want the results to accumulate. * @param startMillis the start time in UTC milliseconds * @param endMillis the end time in UTC milliseconds * @param flags a bit mask of options See * {@link #formatDateRange(Context, Formatter, long, long, int, String) formatDateRange} * @return a string containing the formatted date/time range. */ public static Formatter formatDateRange(Context context, Formatter formatter, long startMillis, long endMillis, int flags) { return formatDateRange(context, formatter, startMillis, endMillis, flags, null); } /** * Formats a date or a time range according to the local conventions. * *
* Example output strings (date formats in these examples are shown using * the US date format convention but that may change depending on the * local settings): *
* The flags argument is a bitmask of options from the following list: * *
* If FORMAT_SHOW_TIME is set, the time is shown as part of the date range. * If the start and end time are the same, then just the start time is * shown. * *
* If FORMAT_SHOW_WEEKDAY is set, then the weekday is shown. * *
* If FORMAT_SHOW_YEAR is set, then the year is always shown. * If FORMAT_SHOW_YEAR is not set, then the year * is shown only if it is different from the current year, or if the start * and end dates fall on different years. * *
* Normally the date is shown unless the start and end day are the same. * If FORMAT_SHOW_DATE is set, then the date is always shown, even for * same day ranges. * *
* If FORMAT_NO_MONTH_DAY is set, then if the date is shown, just the * month name will be shown, not the day of the month. For example, * "January, 2008" instead of "January 6 - 12, 2008". * *
* If FORMAT_CAP_AMPM is set and 12-hour time is used, then the "AM" * and "PM" are capitalized. You should not use this flag * because in some locales these terms cannot be capitalized, and in * many others it doesn't make sense to do so even though it is possible. * *
* If FORMAT_NO_NOON is set and 12-hour time is used, then "12pm" is * shown instead of "noon". * *
* If FORMAT_CAP_NOON is set and 12-hour time is used, then "Noon" is * shown instead of "noon". You should probably not use this flag * because in many locales it will not make sense to capitalize * the term. * *
* If FORMAT_NO_MIDNIGHT is set and 12-hour time is used, then "12am" is * shown instead of "midnight". * *
* If FORMAT_CAP_MIDNIGHT is set and 12-hour time is used, then "Midnight" * is shown instead of "midnight". You should probably not use this * flag because in many locales it will not make sense to capitalize * the term. * *
* If FORMAT_12HOUR is set and the time is shown, then the time is * shown in the 12-hour time format. You should not normally set this. * Instead, let the time format be chosen automatically according to the * system settings. If both FORMAT_12HOUR and FORMAT_24HOUR are set, then * FORMAT_24HOUR takes precedence. * *
* If FORMAT_24HOUR is set and the time is shown, then the time is * shown in the 24-hour time format. You should not normally set this. * Instead, let the time format be chosen automatically according to the * system settings. If both FORMAT_12HOUR and FORMAT_24HOUR are set, then * FORMAT_24HOUR takes precedence. * *
* If FORMAT_UTC is set, then the UTC time zone is used for the start * and end milliseconds unless a time zone is specified. If a time zone * is specified it will be used regardless of the FORMAT_UTC flag. * *
* If FORMAT_ABBREV_TIME is set and 12-hour time format is used, then the * start and end times (if shown) are abbreviated by not showing the minutes * if they are zero. For example, instead of "3:00pm" the time would be * abbreviated to "3pm". * *
* If FORMAT_ABBREV_WEEKDAY is set, then the weekday (if shown) is * abbreviated to a 3-letter string. * *
* If FORMAT_ABBREV_MONTH is set, then the month (if shown) is abbreviated * to a 3-letter string. * *
* If FORMAT_ABBREV_ALL is set, then the weekday and the month (if shown) * are abbreviated to 3-letter strings. * *
* If FORMAT_NUMERIC_DATE is set, then the date is shown in numeric format * instead of using the name of the month. For example, "12/31/2008" * instead of "December 31, 2008". * *
* If the end date ends at 12:00am at the beginning of a day, it is * formatted as the end of the previous day in two scenarios: *
* Example output strings (date formats in these examples are shown using * the US date format convention but that may change depending on the * local settings): *