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