1 /* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package android.text.format; 18 19 import com.android.internal.R; 20 21 import android.content.Context; 22 import android.content.res.Configuration; 23 import android.content.res.Resources; 24 25 import java.util.Calendar; 26 import java.util.Date; 27 import java.util.Formatter; 28 import java.util.GregorianCalendar; 29 import java.util.Locale; 30 import java.util.TimeZone; 31 32 import libcore.icu.LocaleData; 33 34 /** 35 * This class contains various date-related utilities for creating text for things like 36 * elapsed time and date ranges, strings for days of the week and months, and AM/PM text etc. 37 */ 38 public class DateUtils 39 { 40 private static final Object sLock = new Object(); 41 private static Configuration sLastConfig; 42 private static java.text.DateFormat sStatusTimeFormat; 43 private static String sElapsedFormatMMSS; 44 private static String sElapsedFormatHMMSS; 45 46 private static final String FAST_FORMAT_HMMSS = "%1$d:%2$02d:%3$02d"; 47 private static final String FAST_FORMAT_MMSS = "%1$02d:%2$02d"; 48 private static final char TIME_SEPARATOR = ':'; 49 50 51 public static final long SECOND_IN_MILLIS = 1000; 52 public static final long MINUTE_IN_MILLIS = SECOND_IN_MILLIS * 60; 53 public static final long HOUR_IN_MILLIS = MINUTE_IN_MILLIS * 60; 54 public static final long DAY_IN_MILLIS = HOUR_IN_MILLIS * 24; 55 public static final long WEEK_IN_MILLIS = DAY_IN_MILLIS * 7; 56 /** 57 * This constant is actually the length of 364 days, not of a year! 58 */ 59 public static final long YEAR_IN_MILLIS = WEEK_IN_MILLIS * 52; 60 61 // The following FORMAT_* symbols are used for specifying the format of 62 // dates and times in the formatDateRange method. 63 public static final int FORMAT_SHOW_TIME = 0x00001; 64 public static final int FORMAT_SHOW_WEEKDAY = 0x00002; 65 public static final int FORMAT_SHOW_YEAR = 0x00004; 66 public static final int FORMAT_NO_YEAR = 0x00008; 67 public static final int FORMAT_SHOW_DATE = 0x00010; 68 public static final int FORMAT_NO_MONTH_DAY = 0x00020; 69 @Deprecated 70 public static final int FORMAT_12HOUR = 0x00040; 71 @Deprecated 72 public static final int FORMAT_24HOUR = 0x00080; 73 @Deprecated 74 public static final int FORMAT_CAP_AMPM = 0x00100; 75 public static final int FORMAT_NO_NOON = 0x00200; 76 @Deprecated 77 public static final int FORMAT_CAP_NOON = 0x00400; 78 public static final int FORMAT_NO_MIDNIGHT = 0x00800; 79 @Deprecated 80 public static final int FORMAT_CAP_MIDNIGHT = 0x01000; 81 /** 82 * @deprecated Use 83 * {@link #formatDateRange(Context, Formatter, long, long, int, String) formatDateRange} 84 * and pass in {@link Time#TIMEZONE_UTC Time.TIMEZONE_UTC} for the timeZone instead. 85 */ 86 @Deprecated 87 public static final int FORMAT_UTC = 0x02000; 88 public static final int FORMAT_ABBREV_TIME = 0x04000; 89 public static final int FORMAT_ABBREV_WEEKDAY = 0x08000; 90 public static final int FORMAT_ABBREV_MONTH = 0x10000; 91 public static final int FORMAT_NUMERIC_DATE = 0x20000; 92 public static final int FORMAT_ABBREV_RELATIVE = 0x40000; 93 public static final int FORMAT_ABBREV_ALL = 0x80000; 94 @Deprecated 95 public static final int FORMAT_CAP_NOON_MIDNIGHT = (FORMAT_CAP_NOON | FORMAT_CAP_MIDNIGHT); 96 @Deprecated 97 public static final int FORMAT_NO_NOON_MIDNIGHT = (FORMAT_NO_NOON | FORMAT_NO_MIDNIGHT); 98 99 // Date and time format strings that are constant and don't need to be 100 // translated. 101 /** 102 * This is not actually the preferred 24-hour date format in all locales. 103 * @deprecated use {@link java.text.SimpleDateFormat} instead. 104 */ 105 @Deprecated 106 public static final String HOUR_MINUTE_24 = "%H:%M"; 107 public static final String MONTH_FORMAT = "%B"; 108 /** 109 * This is not actually a useful month name in all locales. 110 * @deprecated use {@link java.text.SimpleDateFormat} instead. 111 */ 112 @Deprecated 113 public static final String ABBREV_MONTH_FORMAT = "%b"; 114 public static final String NUMERIC_MONTH_FORMAT = "%m"; 115 public static final String MONTH_DAY_FORMAT = "%-d"; 116 public static final String YEAR_FORMAT = "%Y"; 117 public static final String YEAR_FORMAT_TWO_DIGITS = "%g"; 118 public static final String WEEKDAY_FORMAT = "%A"; 119 public static final String ABBREV_WEEKDAY_FORMAT = "%a"; 120 121 // This table is used to lookup the resource string id of a format string 122 // used for formatting a start and end date that fall in the same year. 123 // The index is constructed from a bit-wise OR of the boolean values: 124 // {showTime, showYear, showWeekDay}. For example, if showYear and 125 // showWeekDay are both true, then the index would be 3. 126 /** @deprecated do not use. */ 127 public static final int sameYearTable[] = { 128 com.android.internal.R.string.same_year_md1_md2, 129 com.android.internal.R.string.same_year_wday1_md1_wday2_md2, 130 com.android.internal.R.string.same_year_mdy1_mdy2, 131 com.android.internal.R.string.same_year_wday1_mdy1_wday2_mdy2, 132 com.android.internal.R.string.same_year_md1_time1_md2_time2, 133 com.android.internal.R.string.same_year_wday1_md1_time1_wday2_md2_time2, 134 com.android.internal.R.string.same_year_mdy1_time1_mdy2_time2, 135 com.android.internal.R.string.same_year_wday1_mdy1_time1_wday2_mdy2_time2, 136 137 // Numeric date strings 138 com.android.internal.R.string.numeric_md1_md2, 139 com.android.internal.R.string.numeric_wday1_md1_wday2_md2, 140 com.android.internal.R.string.numeric_mdy1_mdy2, 141 com.android.internal.R.string.numeric_wday1_mdy1_wday2_mdy2, 142 com.android.internal.R.string.numeric_md1_time1_md2_time2, 143 com.android.internal.R.string.numeric_wday1_md1_time1_wday2_md2_time2, 144 com.android.internal.R.string.numeric_mdy1_time1_mdy2_time2, 145 com.android.internal.R.string.numeric_wday1_mdy1_time1_wday2_mdy2_time2, 146 }; 147 148 // This table is used to lookup the resource string id of a format string 149 // used for formatting a start and end date that fall in the same month. 150 // The index is constructed from a bit-wise OR of the boolean values: 151 // {showTime, showYear, showWeekDay}. For example, if showYear and 152 // showWeekDay are both true, then the index would be 3. 153 /** @deprecated do not use. */ 154 public static final int sameMonthTable[] = { 155 com.android.internal.R.string.same_month_md1_md2, 156 com.android.internal.R.string.same_month_wday1_md1_wday2_md2, 157 com.android.internal.R.string.same_month_mdy1_mdy2, 158 com.android.internal.R.string.same_month_wday1_mdy1_wday2_mdy2, 159 com.android.internal.R.string.same_month_md1_time1_md2_time2, 160 com.android.internal.R.string.same_month_wday1_md1_time1_wday2_md2_time2, 161 com.android.internal.R.string.same_month_mdy1_time1_mdy2_time2, 162 com.android.internal.R.string.same_month_wday1_mdy1_time1_wday2_mdy2_time2, 163 164 com.android.internal.R.string.numeric_md1_md2, 165 com.android.internal.R.string.numeric_wday1_md1_wday2_md2, 166 com.android.internal.R.string.numeric_mdy1_mdy2, 167 com.android.internal.R.string.numeric_wday1_mdy1_wday2_mdy2, 168 com.android.internal.R.string.numeric_md1_time1_md2_time2, 169 com.android.internal.R.string.numeric_wday1_md1_time1_wday2_md2_time2, 170 com.android.internal.R.string.numeric_mdy1_time1_mdy2_time2, 171 com.android.internal.R.string.numeric_wday1_mdy1_time1_wday2_mdy2_time2, 172 }; 173 174 /** 175 * Request the full spelled-out name. For use with the 'abbrev' parameter of 176 * {@link #getDayOfWeekString} and {@link #getMonthString}. 177 * 178 * @more <p> 179 * e.g. "Sunday" or "January" 180 * @deprecated use {@link java.text.SimpleDateFormat} instead. 181 */ 182 @Deprecated 183 public static final int LENGTH_LONG = 10; 184 185 /** 186 * Request an abbreviated version of the name. For use with the 'abbrev' 187 * parameter of {@link #getDayOfWeekString} and {@link #getMonthString}. 188 * 189 * @more <p> 190 * e.g. "Sun" or "Jan" 191 * @deprecated use {@link java.text.SimpleDateFormat} instead. 192 */ 193 @Deprecated 194 public static final int LENGTH_MEDIUM = 20; 195 196 /** 197 * Request a shorter abbreviated version of the name. 198 * For use with the 'abbrev' parameter of {@link #getDayOfWeekString} and {@link #getMonthString}. 199 * @more 200 * <p>e.g. "Su" or "Jan" 201 * <p>In most languages, the results returned for LENGTH_SHORT will be the same as 202 * the results returned for {@link #LENGTH_MEDIUM}. 203 * @deprecated use {@link java.text.SimpleDateFormat} instead. 204 */ 205 @Deprecated 206 public static final int LENGTH_SHORT = 30; 207 208 /** 209 * Request an even shorter abbreviated version of the name. 210 * Do not use this. Currently this will always return the same result 211 * as {@link #LENGTH_SHORT}. 212 * @deprecated use {@link java.text.SimpleDateFormat} instead. 213 */ 214 @Deprecated 215 public static final int LENGTH_SHORTER = 40; 216 217 /** 218 * Request an even shorter abbreviated version of the name. 219 * For use with the 'abbrev' parameter of {@link #getDayOfWeekString} and {@link #getMonthString}. 220 * @more 221 * <p>e.g. "S", "T", "T" or "J" 222 * <p>In some languages, the results returned for LENGTH_SHORTEST will be the same as 223 * the results returned for {@link #LENGTH_SHORT}. 224 * @deprecated use {@link java.text.SimpleDateFormat} instead. 225 */ 226 @Deprecated 227 public static final int LENGTH_SHORTEST = 50; 228 229 /** 230 * Return a string for the day of the week. 231 * @param dayOfWeek One of {@link Calendar#SUNDAY Calendar.SUNDAY}, 232 * {@link Calendar#MONDAY Calendar.MONDAY}, etc. 233 * @param abbrev One of {@link #LENGTH_LONG}, {@link #LENGTH_SHORT}, 234 * {@link #LENGTH_MEDIUM}, or {@link #LENGTH_SHORTEST}. 235 * Note that in most languages, {@link #LENGTH_SHORT} 236 * will return the same as {@link #LENGTH_MEDIUM}. 237 * Undefined lengths will return {@link #LENGTH_MEDIUM} 238 * but may return something different in the future. 239 * @throws IndexOutOfBoundsException if the dayOfWeek is out of bounds. 240 * @deprecated use {@link java.text.SimpleDateFormat} instead. 241 */ 242 @Deprecated getDayOfWeekString(int dayOfWeek, int abbrev)243 public static String getDayOfWeekString(int dayOfWeek, int abbrev) { 244 LocaleData d = LocaleData.get(Locale.getDefault()); 245 String[] names; 246 switch (abbrev) { 247 case LENGTH_LONG: names = d.longWeekdayNames; break; 248 case LENGTH_MEDIUM: names = d.shortWeekdayNames; break; 249 case LENGTH_SHORT: names = d.shortWeekdayNames; break; // TODO 250 case LENGTH_SHORTER: names = d.shortWeekdayNames; break; // TODO 251 case LENGTH_SHORTEST: names = d.tinyWeekdayNames; break; 252 default: names = d.shortWeekdayNames; break; 253 } 254 return names[dayOfWeek]; 255 } 256 257 /** 258 * Return a localized string for AM or PM. 259 * @param ampm Either {@link Calendar#AM Calendar.AM} or {@link Calendar#PM Calendar.PM}. 260 * @throws IndexOutOfBoundsException if the ampm is out of bounds. 261 * @return Localized version of "AM" or "PM". 262 * @deprecated use {@link java.text.SimpleDateFormat} instead. 263 */ 264 @Deprecated getAMPMString(int ampm)265 public static String getAMPMString(int ampm) { 266 return LocaleData.get(Locale.getDefault()).amPm[ampm - Calendar.AM]; 267 } 268 269 /** 270 * Return a localized string for the month of the year. 271 * @param month One of {@link Calendar#JANUARY Calendar.JANUARY}, 272 * {@link Calendar#FEBRUARY Calendar.FEBRUARY}, etc. 273 * @param abbrev One of {@link #LENGTH_LONG}, {@link #LENGTH_MEDIUM}, 274 * or {@link #LENGTH_SHORTEST}. 275 * Undefined lengths will return {@link #LENGTH_MEDIUM} 276 * but may return something different in the future. 277 * @return Localized month of the year. 278 * @deprecated use {@link java.text.SimpleDateFormat} instead. 279 */ 280 @Deprecated getMonthString(int month, int abbrev)281 public static String getMonthString(int month, int abbrev) { 282 // Note that here we use d.shortMonthNames for MEDIUM, SHORT and SHORTER. 283 // This is a shortcut to not spam the translators with too many variations 284 // of the same string. If we find that in a language the distinction 285 // is necessary, we can can add more without changing this API. 286 LocaleData d = LocaleData.get(Locale.getDefault()); 287 String[] names; 288 switch (abbrev) { 289 case LENGTH_LONG: names = d.longMonthNames; break; 290 case LENGTH_MEDIUM: names = d.shortMonthNames; break; 291 case LENGTH_SHORT: names = d.shortMonthNames; break; 292 case LENGTH_SHORTER: names = d.shortMonthNames; break; 293 case LENGTH_SHORTEST: names = d.tinyMonthNames; break; 294 default: names = d.shortMonthNames; break; 295 } 296 return names[month]; 297 } 298 299 /** 300 * Return a localized string for the month of the year, for 301 * contexts where the month is not formatted together with 302 * a day of the month. 303 * 304 * @param month One of {@link Calendar#JANUARY Calendar.JANUARY}, 305 * {@link Calendar#FEBRUARY Calendar.FEBRUARY}, etc. 306 * @param abbrev One of {@link #LENGTH_LONG}, {@link #LENGTH_MEDIUM}, 307 * or {@link #LENGTH_SHORTEST}. 308 * Undefined lengths will return {@link #LENGTH_MEDIUM} 309 * but may return something different in the future. 310 * @return Localized month of the year. 311 * @hide Pending API council approval 312 * @deprecated use {@link java.text.SimpleDateFormat} instead. 313 */ 314 @Deprecated getStandaloneMonthString(int month, int abbrev)315 public static String getStandaloneMonthString(int month, int abbrev) { 316 // Note that here we use d.shortMonthNames for MEDIUM, SHORT and SHORTER. 317 // This is a shortcut to not spam the translators with too many variations 318 // of the same string. If we find that in a language the distinction 319 // is necessary, we can can add more without changing this API. 320 LocaleData d = LocaleData.get(Locale.getDefault()); 321 String[] names; 322 switch (abbrev) { 323 case LENGTH_LONG: names = d.longStandAloneMonthNames; 324 break; 325 case LENGTH_MEDIUM: names = d.shortMonthNames; break; 326 case LENGTH_SHORT: names = d.shortMonthNames; break; 327 case LENGTH_SHORTER: names = d.shortMonthNames; break; 328 case LENGTH_SHORTEST: names = d.tinyMonthNames; break; 329 default: names = d.shortMonthNames; break; 330 } 331 return names[month]; 332 } 333 334 /** 335 * Returns a string describing the elapsed time since startTime. 336 * @param startTime some time in the past. 337 * @return a String object containing the elapsed time. 338 * @see #getRelativeTimeSpanString(long, long, long) 339 */ getRelativeTimeSpanString(long startTime)340 public static CharSequence getRelativeTimeSpanString(long startTime) { 341 return getRelativeTimeSpanString(startTime, System.currentTimeMillis(), MINUTE_IN_MILLIS); 342 } 343 344 /** 345 * Returns a string describing 'time' as a time relative to 'now'. 346 * <p> 347 * Time spans in the past are formatted like "42 minutes ago". 348 * Time spans in the future are formatted like "in 42 minutes". 349 * 350 * @param time the time to describe, in milliseconds 351 * @param now the current time in milliseconds 352 * @param minResolution the minimum timespan to report. For example, a time 3 seconds in the 353 * past will be reported as "0 minutes ago" if this is set to MINUTE_IN_MILLIS. Pass one of 354 * 0, MINUTE_IN_MILLIS, HOUR_IN_MILLIS, DAY_IN_MILLIS, WEEK_IN_MILLIS 355 */ getRelativeTimeSpanString(long time, long now, long minResolution)356 public static CharSequence getRelativeTimeSpanString(long time, long now, long minResolution) { 357 int flags = FORMAT_SHOW_DATE | FORMAT_SHOW_YEAR | FORMAT_ABBREV_MONTH; 358 return getRelativeTimeSpanString(time, now, minResolution, flags); 359 } 360 361 /** 362 * Returns a string describing 'time' as a time relative to 'now'. 363 * <p> 364 * Time spans in the past are formatted like "42 minutes ago". Time spans in 365 * the future are formatted like "in 42 minutes". 366 * <p> 367 * Can use {@link #FORMAT_ABBREV_RELATIVE} flag to use abbreviated relative 368 * times, like "42 mins ago". 369 * 370 * @param time the time to describe, in milliseconds 371 * @param now the current time in milliseconds 372 * @param minResolution the minimum timespan to report. For example, a time 373 * 3 seconds in the past will be reported as "0 minutes ago" if 374 * this is set to MINUTE_IN_MILLIS. Pass one of 0, 375 * MINUTE_IN_MILLIS, HOUR_IN_MILLIS, DAY_IN_MILLIS, 376 * WEEK_IN_MILLIS 377 * @param flags a bit mask of formatting options, such as 378 * {@link #FORMAT_NUMERIC_DATE} or 379 * {@link #FORMAT_ABBREV_RELATIVE} 380 */ getRelativeTimeSpanString(long time, long now, long minResolution, int flags)381 public static CharSequence getRelativeTimeSpanString(long time, long now, long minResolution, 382 int flags) { 383 Resources r = Resources.getSystem(); 384 boolean abbrevRelative = (flags & (FORMAT_ABBREV_RELATIVE | FORMAT_ABBREV_ALL)) != 0; 385 386 boolean past = (now >= time); 387 long duration = Math.abs(now - time); 388 389 int resId; 390 long count; 391 if (duration < MINUTE_IN_MILLIS && minResolution < MINUTE_IN_MILLIS) { 392 count = duration / SECOND_IN_MILLIS; 393 if (past) { 394 if (abbrevRelative) { 395 resId = com.android.internal.R.plurals.abbrev_num_seconds_ago; 396 } else { 397 resId = com.android.internal.R.plurals.num_seconds_ago; 398 } 399 } else { 400 if (abbrevRelative) { 401 resId = com.android.internal.R.plurals.abbrev_in_num_seconds; 402 } else { 403 resId = com.android.internal.R.plurals.in_num_seconds; 404 } 405 } 406 } else if (duration < HOUR_IN_MILLIS && minResolution < HOUR_IN_MILLIS) { 407 count = duration / MINUTE_IN_MILLIS; 408 if (past) { 409 if (abbrevRelative) { 410 resId = com.android.internal.R.plurals.abbrev_num_minutes_ago; 411 } else { 412 resId = com.android.internal.R.plurals.num_minutes_ago; 413 } 414 } else { 415 if (abbrevRelative) { 416 resId = com.android.internal.R.plurals.abbrev_in_num_minutes; 417 } else { 418 resId = com.android.internal.R.plurals.in_num_minutes; 419 } 420 } 421 } else if (duration < DAY_IN_MILLIS && minResolution < DAY_IN_MILLIS) { 422 count = duration / HOUR_IN_MILLIS; 423 if (past) { 424 if (abbrevRelative) { 425 resId = com.android.internal.R.plurals.abbrev_num_hours_ago; 426 } else { 427 resId = com.android.internal.R.plurals.num_hours_ago; 428 } 429 } else { 430 if (abbrevRelative) { 431 resId = com.android.internal.R.plurals.abbrev_in_num_hours; 432 } else { 433 resId = com.android.internal.R.plurals.in_num_hours; 434 } 435 } 436 } else if (duration < WEEK_IN_MILLIS && minResolution < WEEK_IN_MILLIS) { 437 count = getNumberOfDaysPassed(time, now); 438 if (past) { 439 if (abbrevRelative) { 440 resId = com.android.internal.R.plurals.abbrev_num_days_ago; 441 } else { 442 resId = com.android.internal.R.plurals.num_days_ago; 443 } 444 } else { 445 if (abbrevRelative) { 446 resId = com.android.internal.R.plurals.abbrev_in_num_days; 447 } else { 448 resId = com.android.internal.R.plurals.in_num_days; 449 } 450 } 451 } else { 452 // We know that we won't be showing the time, so it is safe to pass 453 // in a null context. 454 return formatDateRange(null, time, time, flags); 455 } 456 457 String format = r.getQuantityString(resId, (int) count); 458 return String.format(format, count); 459 } 460 461 /** 462 * Returns the number of days passed between two dates. 463 * 464 * @param date1 first date 465 * @param date2 second date 466 * @return number of days passed between to dates. 467 */ getNumberOfDaysPassed(long date1, long date2)468 private synchronized static long getNumberOfDaysPassed(long date1, long date2) { 469 if (sThenTime == null) { 470 sThenTime = new Time(); 471 } 472 sThenTime.set(date1); 473 int day1 = Time.getJulianDay(date1, sThenTime.gmtoff); 474 sThenTime.set(date2); 475 int day2 = Time.getJulianDay(date2, sThenTime.gmtoff); 476 return Math.abs(day2 - day1); 477 } 478 479 /** 480 * Return string describing the elapsed time since startTime formatted like 481 * "[relative time/date], [time]". 482 * <p> 483 * Example output strings for the US date format. 484 * <ul> 485 * <li>3 mins ago, 10:15 AM</li> 486 * <li>yesterday, 12:20 PM</li> 487 * <li>Dec 12, 4:12 AM</li> 488 * <li>11/14/2007, 8:20 AM</li> 489 * </ul> 490 * 491 * @param time some time in the past. 492 * @param minResolution the minimum elapsed time (in milliseconds) to report 493 * when showing relative times. For example, a time 3 seconds in 494 * the past will be reported as "0 minutes ago" if this is set to 495 * {@link #MINUTE_IN_MILLIS}. 496 * @param transitionResolution the elapsed time (in milliseconds) at which 497 * to stop reporting relative measurements. Elapsed times greater 498 * than this resolution will default to normal date formatting. 499 * For example, will transition from "6 days ago" to "Dec 12" 500 * when using {@link #WEEK_IN_MILLIS}. 501 */ getRelativeDateTimeString(Context c, long time, long minResolution, long transitionResolution, int flags)502 public static CharSequence getRelativeDateTimeString(Context c, long time, long minResolution, 503 long transitionResolution, int flags) { 504 Resources r = Resources.getSystem(); 505 506 long now = System.currentTimeMillis(); 507 long duration = Math.abs(now - time); 508 509 // getRelativeTimeSpanString() doesn't correctly format relative dates 510 // above a week or exact dates below a day, so clamp 511 // transitionResolution as needed. 512 if (transitionResolution > WEEK_IN_MILLIS) { 513 transitionResolution = WEEK_IN_MILLIS; 514 } else if (transitionResolution < DAY_IN_MILLIS) { 515 transitionResolution = DAY_IN_MILLIS; 516 } 517 518 CharSequence timeClause = formatDateRange(c, time, time, FORMAT_SHOW_TIME); 519 520 String result; 521 if (duration < transitionResolution) { 522 CharSequence relativeClause = getRelativeTimeSpanString(time, now, minResolution, flags); 523 result = r.getString(com.android.internal.R.string.relative_time, relativeClause, timeClause); 524 } else { 525 CharSequence dateClause = getRelativeTimeSpanString(c, time, false); 526 result = r.getString(com.android.internal.R.string.date_time, dateClause, timeClause); 527 } 528 529 return result; 530 } 531 532 /** 533 * Returns a string describing a day relative to the current day. For example if the day is 534 * today this function returns "Today", if the day was a week ago it returns "7 days ago", and 535 * if the day is in 2 weeks it returns "in 14 days". 536 * 537 * @param r the resources to get the strings from 538 * @param day the relative day to describe in UTC milliseconds 539 * @param today the current time in UTC milliseconds 540 * @return a formatting string 541 */ getRelativeDayString(Resources r, long day, long today)542 private static final String getRelativeDayString(Resources r, long day, long today) { 543 Time startTime = new Time(); 544 startTime.set(day); 545 Time currentTime = new Time(); 546 currentTime.set(today); 547 548 int startDay = Time.getJulianDay(day, startTime.gmtoff); 549 int currentDay = Time.getJulianDay(today, currentTime.gmtoff); 550 551 int days = Math.abs(currentDay - startDay); 552 boolean past = (today > day); 553 554 // TODO: some locales name other days too, such as de_DE's "Vorgestern" (today - 2). 555 Locale locale = r.getConfiguration().locale; 556 if (locale == null) { 557 locale = Locale.getDefault(); 558 } 559 if (days == 1) { 560 if (past) { 561 return LocaleData.get(locale).yesterday; 562 } else { 563 return LocaleData.get(locale).tomorrow; 564 } 565 } else if (days == 0) { 566 return LocaleData.get(locale).today; 567 } 568 569 int resId; 570 if (past) { 571 resId = com.android.internal.R.plurals.num_days_ago; 572 } else { 573 resId = com.android.internal.R.plurals.in_num_days; 574 } 575 576 String format = r.getQuantityString(resId, days); 577 return String.format(format, days); 578 } 579 initFormatStrings()580 private static void initFormatStrings() { 581 synchronized (sLock) { 582 initFormatStringsLocked(); 583 } 584 } 585 initFormatStringsLocked()586 private static void initFormatStringsLocked() { 587 Resources r = Resources.getSystem(); 588 Configuration cfg = r.getConfiguration(); 589 if (sLastConfig == null || !sLastConfig.equals(cfg)) { 590 sLastConfig = cfg; 591 sStatusTimeFormat = java.text.DateFormat.getTimeInstance(java.text.DateFormat.SHORT); 592 sElapsedFormatMMSS = r.getString(com.android.internal.R.string.elapsed_time_short_format_mm_ss); 593 sElapsedFormatHMMSS = r.getString(com.android.internal.R.string.elapsed_time_short_format_h_mm_ss); 594 } 595 } 596 597 /** 598 * Format a time so it appears like it would in the status bar clock. 599 * @deprecated use {@link #DateFormat.getTimeFormat(Context)} instead. 600 * @hide 601 */ timeString(long millis)602 public static final CharSequence timeString(long millis) { 603 synchronized (sLock) { 604 initFormatStringsLocked(); 605 return sStatusTimeFormat.format(millis); 606 } 607 } 608 609 /** 610 * Return given duration in a human-friendly format. For example, "4 611 * minutes" or "1 second". Returns only largest meaningful unit of time, 612 * from seconds up to hours. 613 * 614 * @hide 615 */ formatDuration(long millis)616 public static CharSequence formatDuration(long millis) { 617 final Resources res = Resources.getSystem(); 618 if (millis >= HOUR_IN_MILLIS) { 619 final int hours = (int) ((millis + 1800000) / HOUR_IN_MILLIS); 620 return res.getQuantityString( 621 com.android.internal.R.plurals.duration_hours, hours, hours); 622 } else if (millis >= MINUTE_IN_MILLIS) { 623 final int minutes = (int) ((millis + 30000) / MINUTE_IN_MILLIS); 624 return res.getQuantityString( 625 com.android.internal.R.plurals.duration_minutes, minutes, minutes); 626 } else { 627 final int seconds = (int) ((millis + 500) / SECOND_IN_MILLIS); 628 return res.getQuantityString( 629 com.android.internal.R.plurals.duration_seconds, seconds, seconds); 630 } 631 } 632 633 /** 634 * Formats an elapsed time in the form "MM:SS" or "H:MM:SS" 635 * for display on the call-in-progress screen. 636 * @param elapsedSeconds the elapsed time in seconds. 637 */ formatElapsedTime(long elapsedSeconds)638 public static String formatElapsedTime(long elapsedSeconds) { 639 return formatElapsedTime(null, elapsedSeconds); 640 } 641 642 /** 643 * Formats an elapsed time in the form "MM:SS" or "H:MM:SS" 644 * for display on the call-in-progress screen. 645 * 646 * @param recycle {@link StringBuilder} to recycle, if possible 647 * @param elapsedSeconds the elapsed time in seconds. 648 */ formatElapsedTime(StringBuilder recycle, long elapsedSeconds)649 public static String formatElapsedTime(StringBuilder recycle, long elapsedSeconds) { 650 initFormatStrings(); 651 652 long hours = 0; 653 long minutes = 0; 654 long seconds = 0; 655 656 if (elapsedSeconds >= 3600) { 657 hours = elapsedSeconds / 3600; 658 elapsedSeconds -= hours * 3600; 659 } 660 if (elapsedSeconds >= 60) { 661 minutes = elapsedSeconds / 60; 662 elapsedSeconds -= minutes * 60; 663 } 664 seconds = elapsedSeconds; 665 666 String result; 667 if (hours > 0) { 668 return formatElapsedTime(recycle, sElapsedFormatHMMSS, hours, minutes, seconds); 669 } else { 670 return formatElapsedTime(recycle, sElapsedFormatMMSS, minutes, seconds); 671 } 672 } 673 append(StringBuilder sb, long value, boolean pad, char zeroDigit)674 private static void append(StringBuilder sb, long value, boolean pad, char zeroDigit) { 675 if (value < 10) { 676 if (pad) { 677 sb.append(zeroDigit); 678 } 679 } else { 680 sb.append((char) (zeroDigit + (value / 10))); 681 } 682 sb.append((char) (zeroDigit + (value % 10))); 683 } 684 685 /** 686 * Fast formatting of h:mm:ss. 687 */ formatElapsedTime(StringBuilder recycle, String format, long hours, long minutes, long seconds)688 private static String formatElapsedTime(StringBuilder recycle, String format, long hours, 689 long minutes, long seconds) { 690 if (FAST_FORMAT_HMMSS.equals(format)) { 691 char zeroDigit = LocaleData.get(Locale.getDefault()).zeroDigit; 692 693 StringBuilder sb = recycle; 694 if (sb == null) { 695 sb = new StringBuilder(8); 696 } else { 697 sb.setLength(0); 698 } 699 append(sb, hours, false, zeroDigit); 700 sb.append(TIME_SEPARATOR); 701 append(sb, minutes, true, zeroDigit); 702 sb.append(TIME_SEPARATOR); 703 append(sb, seconds, true, zeroDigit); 704 return sb.toString(); 705 } else { 706 return String.format(format, hours, minutes, seconds); 707 } 708 } 709 710 /** 711 * Fast formatting of mm:ss. 712 */ formatElapsedTime(StringBuilder recycle, String format, long minutes, long seconds)713 private static String formatElapsedTime(StringBuilder recycle, String format, long minutes, 714 long seconds) { 715 if (FAST_FORMAT_MMSS.equals(format)) { 716 char zeroDigit = LocaleData.get(Locale.getDefault()).zeroDigit; 717 718 StringBuilder sb = recycle; 719 if (sb == null) { 720 sb = new StringBuilder(8); 721 } else { 722 sb.setLength(0); 723 } 724 append(sb, minutes, false, zeroDigit); 725 sb.append(TIME_SEPARATOR); 726 append(sb, seconds, true, zeroDigit); 727 return sb.toString(); 728 } else { 729 return String.format(format, minutes, seconds); 730 } 731 } 732 733 /** 734 * Format a date / time such that if the then is on the same day as now, it shows 735 * just the time and if it's a different day, it shows just the date. 736 * 737 * <p>The parameters dateFormat and timeFormat should each be one of 738 * {@link java.text.DateFormat#DEFAULT}, 739 * {@link java.text.DateFormat#FULL}, 740 * {@link java.text.DateFormat#LONG}, 741 * {@link java.text.DateFormat#MEDIUM} 742 * or 743 * {@link java.text.DateFormat#SHORT} 744 * 745 * @param then the date to format 746 * @param now the base time 747 * @param dateStyle how to format the date portion. 748 * @param timeStyle how to format the time portion. 749 */ formatSameDayTime(long then, long now, int dateStyle, int timeStyle)750 public static final CharSequence formatSameDayTime(long then, long now, 751 int dateStyle, int timeStyle) { 752 Calendar thenCal = new GregorianCalendar(); 753 thenCal.setTimeInMillis(then); 754 Date thenDate = thenCal.getTime(); 755 Calendar nowCal = new GregorianCalendar(); 756 nowCal.setTimeInMillis(now); 757 758 java.text.DateFormat f; 759 760 if (thenCal.get(Calendar.YEAR) == nowCal.get(Calendar.YEAR) 761 && thenCal.get(Calendar.MONTH) == nowCal.get(Calendar.MONTH) 762 && thenCal.get(Calendar.DAY_OF_MONTH) == nowCal.get(Calendar.DAY_OF_MONTH)) { 763 f = java.text.DateFormat.getTimeInstance(timeStyle); 764 } else { 765 f = java.text.DateFormat.getDateInstance(dateStyle); 766 } 767 return f.format(thenDate); 768 } 769 770 /** 771 * @hide 772 * @deprecated use {@link android.text.format.Time} 773 */ newCalendar(boolean zulu)774 public static Calendar newCalendar(boolean zulu) 775 { 776 if (zulu) 777 return Calendar.getInstance(TimeZone.getTimeZone("GMT")); 778 779 return Calendar.getInstance(); 780 } 781 782 /** 783 * @return true if the supplied when is today else false 784 */ isToday(long when)785 public static boolean isToday(long when) { 786 Time time = new Time(); 787 time.set(when); 788 789 int thenYear = time.year; 790 int thenMonth = time.month; 791 int thenMonthDay = time.monthDay; 792 793 time.set(System.currentTimeMillis()); 794 return (thenYear == time.year) 795 && (thenMonth == time.month) 796 && (thenMonthDay == time.monthDay); 797 } 798 799 /** 800 * @hide 801 * @deprecated use {@link android.text.format.Time} 802 * Return true if this date string is local time 803 */ isUTC(String s)804 public static boolean isUTC(String s) 805 { 806 if (s.length() == 16 && s.charAt(15) == 'Z') { 807 return true; 808 } 809 if (s.length() == 9 && s.charAt(8) == 'Z') { 810 // XXX not sure if this case possible/valid 811 return true; 812 } 813 return false; 814 } 815 816 /** 817 * Return a string containing the date and time in RFC2445 format. 818 * Ensures that the time is written in UTC. The Calendar class doesn't 819 * really help out with this, so this is slower than it ought to be. 820 * 821 * @param cal the date and time to write 822 * @hide 823 * @deprecated use {@link android.text.format.Time} 824 */ writeDateTime(Calendar cal)825 public static String writeDateTime(Calendar cal) 826 { 827 TimeZone tz = TimeZone.getTimeZone("GMT"); 828 GregorianCalendar c = new GregorianCalendar(tz); 829 c.setTimeInMillis(cal.getTimeInMillis()); 830 return writeDateTime(c, true); 831 } 832 833 /** 834 * Return a string containing the date and time in RFC2445 format. 835 * 836 * @param cal the date and time to write 837 * @param zulu If the calendar is in UTC, pass true, and a Z will 838 * be written at the end as per RFC2445. Otherwise, the time is 839 * considered in localtime. 840 * @hide 841 * @deprecated use {@link android.text.format.Time} 842 */ writeDateTime(Calendar cal, boolean zulu)843 public static String writeDateTime(Calendar cal, boolean zulu) 844 { 845 StringBuilder sb = new StringBuilder(); 846 sb.ensureCapacity(16); 847 if (zulu) { 848 sb.setLength(16); 849 sb.setCharAt(15, 'Z'); 850 } else { 851 sb.setLength(15); 852 } 853 return writeDateTime(cal, sb); 854 } 855 856 /** 857 * Return a string containing the date and time in RFC2445 format. 858 * 859 * @param cal the date and time to write 860 * @param sb a StringBuilder to use. It is assumed that setLength 861 * has already been called on sb to the appropriate length 862 * which is sb.setLength(zulu ? 16 : 15) 863 * @hide 864 * @deprecated use {@link android.text.format.Time} 865 */ writeDateTime(Calendar cal, StringBuilder sb)866 public static String writeDateTime(Calendar cal, StringBuilder sb) 867 { 868 int n; 869 870 n = cal.get(Calendar.YEAR); 871 sb.setCharAt(3, (char)('0'+n%10)); 872 n /= 10; 873 sb.setCharAt(2, (char)('0'+n%10)); 874 n /= 10; 875 sb.setCharAt(1, (char)('0'+n%10)); 876 n /= 10; 877 sb.setCharAt(0, (char)('0'+n%10)); 878 879 n = cal.get(Calendar.MONTH) + 1; 880 sb.setCharAt(5, (char)('0'+n%10)); 881 n /= 10; 882 sb.setCharAt(4, (char)('0'+n%10)); 883 884 n = cal.get(Calendar.DAY_OF_MONTH); 885 sb.setCharAt(7, (char)('0'+n%10)); 886 n /= 10; 887 sb.setCharAt(6, (char)('0'+n%10)); 888 889 sb.setCharAt(8, 'T'); 890 891 n = cal.get(Calendar.HOUR_OF_DAY); 892 sb.setCharAt(10, (char)('0'+n%10)); 893 n /= 10; 894 sb.setCharAt(9, (char)('0'+n%10)); 895 896 n = cal.get(Calendar.MINUTE); 897 sb.setCharAt(12, (char)('0'+n%10)); 898 n /= 10; 899 sb.setCharAt(11, (char)('0'+n%10)); 900 901 n = cal.get(Calendar.SECOND); 902 sb.setCharAt(14, (char)('0'+n%10)); 903 n /= 10; 904 sb.setCharAt(13, (char)('0'+n%10)); 905 906 return sb.toString(); 907 } 908 909 /** 910 * @hide 911 * @deprecated use {@link android.text.format.Time} 912 */ assign(Calendar lval, Calendar rval)913 public static void assign(Calendar lval, Calendar rval) 914 { 915 // there should be a faster way. 916 lval.clear(); 917 lval.setTimeInMillis(rval.getTimeInMillis()); 918 } 919 920 /** 921 * Formats a date or a time range according to the local conventions. 922 * <p> 923 * Note that this is a convenience method. Using it involves creating an 924 * internal {@link java.util.Formatter} instance on-the-fly, which is 925 * somewhat costly in terms of memory and time. This is probably acceptable 926 * if you use the method only rarely, but if you rely on it for formatting a 927 * large number of dates, consider creating and reusing your own 928 * {@link java.util.Formatter} instance and use the version of 929 * {@link #formatDateRange(Context, long, long, int) formatDateRange} 930 * that takes a {@link java.util.Formatter}. 931 * 932 * @param context the context is required only if the time is shown 933 * @param startMillis the start time in UTC milliseconds 934 * @param endMillis the end time in UTC milliseconds 935 * @param flags a bit mask of options See 936 * {@link #formatDateRange(Context, Formatter, long, long, int, String) formatDateRange} 937 * @return a string containing the formatted date/time range. 938 */ formatDateRange(Context context, long startMillis, long endMillis, int flags)939 public static String formatDateRange(Context context, long startMillis, 940 long endMillis, int flags) { 941 Formatter f = new Formatter(new StringBuilder(50), Locale.getDefault()); 942 return formatDateRange(context, f, startMillis, endMillis, flags).toString(); 943 } 944 945 /** 946 * Formats a date or a time range according to the local conventions. 947 * <p> 948 * Note that this is a convenience method for formatting the date or 949 * time range in the local time zone. If you want to specify the time 950 * zone please use 951 * {@link #formatDateRange(Context, Formatter, long, long, int, String) formatDateRange}. 952 * 953 * @param context the context is required only if the time is shown 954 * @param formatter the Formatter used for formatting the date range. 955 * Note: be sure to call setLength(0) on StringBuilder passed to 956 * the Formatter constructor unless you want the results to accumulate. 957 * @param startMillis the start time in UTC milliseconds 958 * @param endMillis the end time in UTC milliseconds 959 * @param flags a bit mask of options See 960 * {@link #formatDateRange(Context, Formatter, long, long, int, String) formatDateRange} 961 * @return a string containing the formatted date/time range. 962 */ formatDateRange(Context context, Formatter formatter, long startMillis, long endMillis, int flags)963 public static Formatter formatDateRange(Context context, Formatter formatter, long startMillis, 964 long endMillis, int flags) { 965 return formatDateRange(context, formatter, startMillis, endMillis, flags, null); 966 } 967 968 /** 969 * Formats a date or a time range according to the local conventions. 970 * 971 * <p> 972 * Example output strings (date formats in these examples are shown using 973 * the US date format convention but that may change depending on the 974 * local settings): 975 * <ul> 976 * <li>10:15am</li> 977 * <li>3:00pm - 4:00pm</li> 978 * <li>3pm - 4pm</li> 979 * <li>3PM - 4PM</li> 980 * <li>08:00 - 17:00</li> 981 * <li>Oct 9</li> 982 * <li>Tue, Oct 9</li> 983 * <li>October 9, 2007</li> 984 * <li>Oct 9 - 10</li> 985 * <li>Oct 9 - 10, 2007</li> 986 * <li>Oct 28 - Nov 3, 2007</li> 987 * <li>Dec 31, 2007 - Jan 1, 2008</li> 988 * <li>Oct 9, 8:00am - Oct 10, 5:00pm</li> 989 * <li>12/31/2007 - 01/01/2008</li> 990 * </ul> 991 * 992 * <p> 993 * The flags argument is a bitmask of options from the following list: 994 * 995 * <ul> 996 * <li>FORMAT_SHOW_TIME</li> 997 * <li>FORMAT_SHOW_WEEKDAY</li> 998 * <li>FORMAT_SHOW_YEAR</li> 999 * <li>FORMAT_NO_YEAR</li> 1000 * <li>FORMAT_SHOW_DATE</li> 1001 * <li>FORMAT_NO_MONTH_DAY</li> 1002 * <li>FORMAT_12HOUR</li> 1003 * <li>FORMAT_24HOUR</li> 1004 * <li>FORMAT_CAP_AMPM</li> 1005 * <li>FORMAT_NO_NOON</li> 1006 * <li>FORMAT_CAP_NOON</li> 1007 * <li>FORMAT_NO_MIDNIGHT</li> 1008 * <li>FORMAT_CAP_MIDNIGHT</li> 1009 * <li>FORMAT_UTC</li> 1010 * <li>FORMAT_ABBREV_TIME</li> 1011 * <li>FORMAT_ABBREV_WEEKDAY</li> 1012 * <li>FORMAT_ABBREV_MONTH</li> 1013 * <li>FORMAT_ABBREV_ALL</li> 1014 * <li>FORMAT_NUMERIC_DATE</li> 1015 * </ul> 1016 * 1017 * <p> 1018 * If FORMAT_SHOW_TIME is set, the time is shown as part of the date range. 1019 * If the start and end time are the same, then just the start time is 1020 * shown. 1021 * 1022 * <p> 1023 * If FORMAT_SHOW_WEEKDAY is set, then the weekday is shown. 1024 * 1025 * <p> 1026 * If FORMAT_SHOW_YEAR is set, then the year is always shown. 1027 * If FORMAT_NO_YEAR is set, then the year is not shown. 1028 * If neither FORMAT_SHOW_YEAR nor FORMAT_NO_YEAR are set, then the year 1029 * is shown only if it is different from the current year, or if the start 1030 * and end dates fall on different years. If both are set, 1031 * FORMAT_SHOW_YEAR takes precedence. 1032 * 1033 * <p> 1034 * Normally the date is shown unless the start and end day are the same. 1035 * If FORMAT_SHOW_DATE is set, then the date is always shown, even for 1036 * same day ranges. 1037 * 1038 * <p> 1039 * If FORMAT_NO_MONTH_DAY is set, then if the date is shown, just the 1040 * month name will be shown, not the day of the month. For example, 1041 * "January, 2008" instead of "January 6 - 12, 2008". 1042 * 1043 * <p> 1044 * If FORMAT_CAP_AMPM is set and 12-hour time is used, then the "AM" 1045 * and "PM" are capitalized. You should not use this flag 1046 * because in some locales these terms cannot be capitalized, and in 1047 * many others it doesn't make sense to do so even though it is possible. 1048 * 1049 * <p> 1050 * If FORMAT_NO_NOON is set and 12-hour time is used, then "12pm" is 1051 * shown instead of "noon". 1052 * 1053 * <p> 1054 * If FORMAT_CAP_NOON is set and 12-hour time is used, then "Noon" is 1055 * shown instead of "noon". You should probably not use this flag 1056 * because in many locales it will not make sense to capitalize 1057 * the term. 1058 * 1059 * <p> 1060 * If FORMAT_NO_MIDNIGHT is set and 12-hour time is used, then "12am" is 1061 * shown instead of "midnight". 1062 * 1063 * <p> 1064 * If FORMAT_CAP_MIDNIGHT is set and 12-hour time is used, then "Midnight" 1065 * is shown instead of "midnight". You should probably not use this 1066 * flag because in many locales it will not make sense to capitalize 1067 * the term. 1068 * 1069 * <p> 1070 * If FORMAT_12HOUR is set and the time is shown, then the time is 1071 * shown in the 12-hour time format. You should not normally set this. 1072 * Instead, let the time format be chosen automatically according to the 1073 * system settings. If both FORMAT_12HOUR and FORMAT_24HOUR are set, then 1074 * FORMAT_24HOUR takes precedence. 1075 * 1076 * <p> 1077 * If FORMAT_24HOUR is set and the time is shown, then the time is 1078 * shown in the 24-hour time format. You should not normally set this. 1079 * Instead, let the time format be chosen automatically according to the 1080 * system settings. If both FORMAT_12HOUR and FORMAT_24HOUR are set, then 1081 * FORMAT_24HOUR takes precedence. 1082 * 1083 * <p> 1084 * If FORMAT_UTC is set, then the UTC time zone is used for the start 1085 * and end milliseconds unless a time zone is specified. If a time zone 1086 * is specified it will be used regardless of the FORMAT_UTC flag. 1087 * 1088 * <p> 1089 * If FORMAT_ABBREV_TIME is set and 12-hour time format is used, then the 1090 * start and end times (if shown) are abbreviated by not showing the minutes 1091 * if they are zero. For example, instead of "3:00pm" the time would be 1092 * abbreviated to "3pm". 1093 * 1094 * <p> 1095 * If FORMAT_ABBREV_WEEKDAY is set, then the weekday (if shown) is 1096 * abbreviated to a 3-letter string. 1097 * 1098 * <p> 1099 * If FORMAT_ABBREV_MONTH is set, then the month (if shown) is abbreviated 1100 * to a 3-letter string. 1101 * 1102 * <p> 1103 * If FORMAT_ABBREV_ALL is set, then the weekday and the month (if shown) 1104 * are abbreviated to 3-letter strings. 1105 * 1106 * <p> 1107 * If FORMAT_NUMERIC_DATE is set, then the date is shown in numeric format 1108 * instead of using the name of the month. For example, "12/31/2008" 1109 * instead of "December 31, 2008". 1110 * 1111 * <p> 1112 * If the end date ends at 12:00am at the beginning of a day, it is 1113 * formatted as the end of the previous day in two scenarios: 1114 * <ul> 1115 * <li>For single day events. This results in "8pm - midnight" instead of 1116 * "Nov 10, 8pm - Nov 11, 12am".</li> 1117 * <li>When the time is not displayed. This results in "Nov 10 - 11" for 1118 * an event with a start date of Nov 10 and an end date of Nov 12 at 1119 * 00:00.</li> 1120 * </ul> 1121 * 1122 * @param context the context is required only if the time is shown 1123 * @param formatter the Formatter used for formatting the date range. 1124 * Note: be sure to call setLength(0) on StringBuilder passed to 1125 * the Formatter constructor unless you want the results to accumulate. 1126 * @param startMillis the start time in UTC milliseconds 1127 * @param endMillis the end time in UTC milliseconds 1128 * @param flags a bit mask of options 1129 * @param timeZone the time zone to compute the string in. Use null for local 1130 * or if the FORMAT_UTC flag is being used. 1131 * 1132 * @return the formatter with the formatted date/time range appended to the string buffer. 1133 */ formatDateRange(Context context, Formatter formatter, long startMillis, long endMillis, int flags, String timeZone)1134 public static Formatter formatDateRange(Context context, Formatter formatter, long startMillis, 1135 long endMillis, int flags, String timeZone) { 1136 Resources res = Resources.getSystem(); 1137 boolean showTime = (flags & FORMAT_SHOW_TIME) != 0; 1138 boolean showWeekDay = (flags & FORMAT_SHOW_WEEKDAY) != 0; 1139 boolean showYear = (flags & FORMAT_SHOW_YEAR) != 0; 1140 boolean noYear = (flags & FORMAT_NO_YEAR) != 0; 1141 boolean useUTC = (flags & FORMAT_UTC) != 0; 1142 boolean abbrevWeekDay = (flags & (FORMAT_ABBREV_WEEKDAY | FORMAT_ABBREV_ALL)) != 0; 1143 boolean abbrevMonth = (flags & (FORMAT_ABBREV_MONTH | FORMAT_ABBREV_ALL)) != 0; 1144 boolean noMonthDay = (flags & FORMAT_NO_MONTH_DAY) != 0; 1145 boolean numericDate = (flags & FORMAT_NUMERIC_DATE) != 0; 1146 1147 // If we're getting called with a single instant in time (from 1148 // e.g. formatDateTime(), below), then we can skip a lot of 1149 // computation below that'd otherwise be thrown out. 1150 boolean isInstant = (startMillis == endMillis); 1151 1152 Time startDate; 1153 if (timeZone != null) { 1154 startDate = new Time(timeZone); 1155 } else if (useUTC) { 1156 startDate = new Time(Time.TIMEZONE_UTC); 1157 } else { 1158 startDate = new Time(); 1159 } 1160 startDate.set(startMillis); 1161 1162 Time endDate; 1163 int dayDistance; 1164 if (isInstant) { 1165 endDate = startDate; 1166 dayDistance = 0; 1167 } else { 1168 if (timeZone != null) { 1169 endDate = new Time(timeZone); 1170 } else if (useUTC) { 1171 endDate = new Time(Time.TIMEZONE_UTC); 1172 } else { 1173 endDate = new Time(); 1174 } 1175 endDate.set(endMillis); 1176 int startJulianDay = Time.getJulianDay(startMillis, startDate.gmtoff); 1177 int endJulianDay = Time.getJulianDay(endMillis, endDate.gmtoff); 1178 dayDistance = endJulianDay - startJulianDay; 1179 } 1180 1181 if (!isInstant 1182 && (endDate.hour | endDate.minute | endDate.second) == 0 1183 && (!showTime || dayDistance <= 1)) { 1184 endDate.monthDay -= 1; 1185 endDate.normalize(true /* ignore isDst */); 1186 } 1187 1188 int startDay = startDate.monthDay; 1189 int startMonthNum = startDate.month; 1190 int startYear = startDate.year; 1191 1192 int endDay = endDate.monthDay; 1193 int endMonthNum = endDate.month; 1194 int endYear = endDate.year; 1195 1196 String startWeekDayString = ""; 1197 String endWeekDayString = ""; 1198 if (showWeekDay) { 1199 String weekDayFormat = ""; 1200 if (abbrevWeekDay) { 1201 weekDayFormat = ABBREV_WEEKDAY_FORMAT; 1202 } else { 1203 weekDayFormat = WEEKDAY_FORMAT; 1204 } 1205 startWeekDayString = startDate.format(weekDayFormat); 1206 endWeekDayString = isInstant ? startWeekDayString : endDate.format(weekDayFormat); 1207 } 1208 1209 String startTimeString = ""; 1210 String endTimeString = ""; 1211 if (showTime) { 1212 String startTimeFormat = ""; 1213 String endTimeFormat = ""; 1214 boolean force24Hour = (flags & FORMAT_24HOUR) != 0; 1215 boolean force12Hour = (flags & FORMAT_12HOUR) != 0; 1216 boolean use24Hour; 1217 if (force24Hour) { 1218 use24Hour = true; 1219 } else if (force12Hour) { 1220 use24Hour = false; 1221 } else { 1222 use24Hour = DateFormat.is24HourFormat(context); 1223 } 1224 if (use24Hour) { 1225 startTimeFormat = endTimeFormat = 1226 res.getString(com.android.internal.R.string.hour_minute_24); 1227 } else { 1228 boolean abbrevTime = (flags & (FORMAT_ABBREV_TIME | FORMAT_ABBREV_ALL)) != 0; 1229 boolean capAMPM = (flags & FORMAT_CAP_AMPM) != 0; 1230 boolean noNoon = (flags & FORMAT_NO_NOON) != 0; 1231 boolean capNoon = (flags & FORMAT_CAP_NOON) != 0; 1232 boolean noMidnight = (flags & FORMAT_NO_MIDNIGHT) != 0; 1233 boolean capMidnight = (flags & FORMAT_CAP_MIDNIGHT) != 0; 1234 1235 boolean startOnTheHour = startDate.minute == 0 && startDate.second == 0; 1236 boolean endOnTheHour = endDate.minute == 0 && endDate.second == 0; 1237 if (abbrevTime && startOnTheHour) { 1238 if (capAMPM) { 1239 startTimeFormat = res.getString(com.android.internal.R.string.hour_cap_ampm); 1240 } else { 1241 startTimeFormat = res.getString(com.android.internal.R.string.hour_ampm); 1242 } 1243 } else { 1244 if (capAMPM) { 1245 startTimeFormat = res.getString(com.android.internal.R.string.hour_minute_cap_ampm); 1246 } else { 1247 startTimeFormat = res.getString(com.android.internal.R.string.hour_minute_ampm); 1248 } 1249 } 1250 1251 // Don't waste time on setting endTimeFormat when 1252 // we're dealing with an instant, where we'll never 1253 // need the end point. (It's the same as the start 1254 // point) 1255 if (!isInstant) { 1256 if (abbrevTime && endOnTheHour) { 1257 if (capAMPM) { 1258 endTimeFormat = res.getString(com.android.internal.R.string.hour_cap_ampm); 1259 } else { 1260 endTimeFormat = res.getString(com.android.internal.R.string.hour_ampm); 1261 } 1262 } else { 1263 if (capAMPM) { 1264 endTimeFormat = res.getString(com.android.internal.R.string.hour_minute_cap_ampm); 1265 } else { 1266 endTimeFormat = res.getString(com.android.internal.R.string.hour_minute_ampm); 1267 } 1268 } 1269 1270 if (endDate.hour == 12 && endOnTheHour && !noNoon) { 1271 if (capNoon) { 1272 endTimeFormat = res.getString(com.android.internal.R.string.Noon); 1273 } else { 1274 endTimeFormat = res.getString(com.android.internal.R.string.noon); 1275 } 1276 } else if (endDate.hour == 0 && endOnTheHour && !noMidnight) { 1277 if (capMidnight) { 1278 endTimeFormat = res.getString(com.android.internal.R.string.Midnight); 1279 } else { 1280 endTimeFormat = res.getString(com.android.internal.R.string.midnight); 1281 } 1282 } 1283 } 1284 1285 if (startDate.hour == 12 && startOnTheHour && !noNoon) { 1286 if (capNoon) { 1287 startTimeFormat = res.getString(com.android.internal.R.string.Noon); 1288 } else { 1289 startTimeFormat = res.getString(com.android.internal.R.string.noon); 1290 } 1291 // Don't show the start time starting at midnight. Show 1292 // 12am instead. 1293 } 1294 } 1295 1296 startTimeString = startDate.format(startTimeFormat); 1297 endTimeString = isInstant ? startTimeString : endDate.format(endTimeFormat); 1298 } 1299 1300 // Show the year if the user specified FORMAT_SHOW_YEAR or if 1301 // the starting and end years are different from each other 1302 // or from the current year. But don't show the year if the 1303 // user specified FORMAT_NO_YEAR. 1304 if (showYear) { 1305 // No code... just a comment for clarity. Keep showYear 1306 // on, as they enabled it with FORMAT_SHOW_YEAR. This 1307 // takes precedence over them setting FORMAT_NO_YEAR. 1308 } else if (noYear) { 1309 // They explicitly didn't want a year. 1310 showYear = false; 1311 } else if (startYear != endYear) { 1312 showYear = true; 1313 } else { 1314 // Show the year if it's not equal to the current year. 1315 Time currentTime = new Time(); 1316 currentTime.setToNow(); 1317 showYear = startYear != currentTime.year; 1318 } 1319 1320 String defaultDateFormat, fullFormat, dateRange; 1321 if (numericDate) { 1322 defaultDateFormat = res.getString(com.android.internal.R.string.numeric_date); 1323 } else if (showYear) { 1324 if (abbrevMonth) { 1325 if (noMonthDay) { 1326 defaultDateFormat = res.getString(com.android.internal.R.string.abbrev_month_year); 1327 } else { 1328 defaultDateFormat = res.getString(com.android.internal.R.string.abbrev_month_day_year); 1329 } 1330 } else { 1331 if (noMonthDay) { 1332 defaultDateFormat = res.getString(com.android.internal.R.string.month_year); 1333 } else { 1334 defaultDateFormat = res.getString(com.android.internal.R.string.month_day_year); 1335 } 1336 } 1337 } else { 1338 if (abbrevMonth) { 1339 if (noMonthDay) { 1340 defaultDateFormat = res.getString(com.android.internal.R.string.abbrev_month); 1341 } else { 1342 defaultDateFormat = res.getString(com.android.internal.R.string.abbrev_month_day); 1343 } 1344 } else { 1345 if (noMonthDay) { 1346 defaultDateFormat = res.getString(com.android.internal.R.string.month); 1347 } else { 1348 defaultDateFormat = res.getString(com.android.internal.R.string.month_day); 1349 } 1350 } 1351 } 1352 1353 if (showWeekDay) { 1354 if (showTime) { 1355 fullFormat = res.getString(com.android.internal.R.string.wday1_date1_time1_wday2_date2_time2); 1356 } else { 1357 fullFormat = res.getString(com.android.internal.R.string.wday1_date1_wday2_date2); 1358 } 1359 } else { 1360 if (showTime) { 1361 fullFormat = res.getString(com.android.internal.R.string.date1_time1_date2_time2); 1362 } else { 1363 fullFormat = res.getString(com.android.internal.R.string.date1_date2); 1364 } 1365 } 1366 1367 if (noMonthDay && startMonthNum == endMonthNum && startYear == endYear) { 1368 // Example: "January, 2008" 1369 return formatter.format("%s", startDate.format(defaultDateFormat)); 1370 } 1371 1372 if (startYear != endYear || noMonthDay) { 1373 // Different year or we are not showing the month day number. 1374 // Example: "December 31, 2007 - January 1, 2008" 1375 // Or: "January - February, 2008" 1376 String startDateString = startDate.format(defaultDateFormat); 1377 String endDateString = endDate.format(defaultDateFormat); 1378 1379 // The values that are used in a fullFormat string are specified 1380 // by position. 1381 return formatter.format(fullFormat, 1382 startWeekDayString, startDateString, startTimeString, 1383 endWeekDayString, endDateString, endTimeString); 1384 } 1385 1386 // Get the month, day, and year strings for the start and end dates 1387 String monthFormat; 1388 if (numericDate) { 1389 monthFormat = NUMERIC_MONTH_FORMAT; 1390 } else if (abbrevMonth) { 1391 monthFormat = 1392 res.getString(com.android.internal.R.string.short_format_month); 1393 } else { 1394 monthFormat = MONTH_FORMAT; 1395 } 1396 String startMonthString = startDate.format(monthFormat); 1397 String startMonthDayString = startDate.format(MONTH_DAY_FORMAT); 1398 String startYearString = startDate.format(YEAR_FORMAT); 1399 1400 String endMonthString = isInstant ? null : endDate.format(monthFormat); 1401 String endMonthDayString = isInstant ? null : endDate.format(MONTH_DAY_FORMAT); 1402 String endYearString = isInstant ? null : endDate.format(YEAR_FORMAT); 1403 1404 String startStandaloneMonthString = startMonthString; 1405 String endStandaloneMonthString = endMonthString; 1406 // We need standalone months for these strings in Persian (fa): http://b/6811327 1407 if (!numericDate && !abbrevMonth && Locale.getDefault().getLanguage().equals("fa")) { 1408 startStandaloneMonthString = startDate.format("%-B"); 1409 endStandaloneMonthString = endDate.format("%-B"); 1410 } 1411 1412 if (startMonthNum != endMonthNum) { 1413 // Same year, different month. 1414 // Example: "October 28 - November 3" 1415 // or: "Wed, Oct 31 - Sat, Nov 3, 2007" 1416 // or: "Oct 31, 8am - Sat, Nov 3, 2007, 5pm" 1417 1418 int index = 0; 1419 if (showWeekDay) index = 1; 1420 if (showYear) index += 2; 1421 if (showTime) index += 4; 1422 if (numericDate) index += 8; 1423 int resId = sameYearTable[index]; 1424 fullFormat = res.getString(resId); 1425 1426 // The values that are used in a fullFormat string are specified 1427 // by position. 1428 return formatter.format(fullFormat, 1429 startWeekDayString, startMonthString, startMonthDayString, 1430 startYearString, startTimeString, 1431 endWeekDayString, endMonthString, endMonthDayString, 1432 endYearString, endTimeString, 1433 startStandaloneMonthString, endStandaloneMonthString); 1434 } 1435 1436 if (startDay != endDay) { 1437 // Same month, different day. 1438 int index = 0; 1439 if (showWeekDay) index = 1; 1440 if (showYear) index += 2; 1441 if (showTime) index += 4; 1442 if (numericDate) index += 8; 1443 int resId = sameMonthTable[index]; 1444 fullFormat = res.getString(resId); 1445 1446 // The values that are used in a fullFormat string are specified 1447 // by position. 1448 return formatter.format(fullFormat, 1449 startWeekDayString, startMonthString, startMonthDayString, 1450 startYearString, startTimeString, 1451 endWeekDayString, endMonthString, endMonthDayString, 1452 endYearString, endTimeString, 1453 startStandaloneMonthString, endStandaloneMonthString); 1454 } 1455 1456 // Same start and end day 1457 boolean showDate = (flags & FORMAT_SHOW_DATE) != 0; 1458 1459 // If nothing was specified, then show the date. 1460 if (!showTime && !showDate && !showWeekDay) showDate = true; 1461 1462 // Compute the time string (example: "10:00 - 11:00 am") 1463 String timeString = ""; 1464 if (showTime) { 1465 // If the start and end time are the same, then just show the 1466 // start time. 1467 if (isInstant) { 1468 // Same start and end time. 1469 // Example: "10:15 AM" 1470 timeString = startTimeString; 1471 } else { 1472 // Example: "10:00 - 11:00 am" 1473 String timeFormat = res.getString(com.android.internal.R.string.time1_time2); 1474 // Don't use the user supplied Formatter because the result will pollute the buffer. 1475 timeString = String.format(timeFormat, startTimeString, endTimeString); 1476 } 1477 } 1478 1479 // Figure out which full format to use. 1480 fullFormat = ""; 1481 String dateString = ""; 1482 if (showDate) { 1483 dateString = startDate.format(defaultDateFormat); 1484 if (showWeekDay) { 1485 if (showTime) { 1486 // Example: "10:00 - 11:00 am, Tue, Oct 9" 1487 fullFormat = res.getString(com.android.internal.R.string.time_wday_date); 1488 } else { 1489 // Example: "Tue, Oct 9" 1490 fullFormat = res.getString(com.android.internal.R.string.wday_date); 1491 } 1492 } else { 1493 if (showTime) { 1494 // Example: "10:00 - 11:00 am, Oct 9" 1495 fullFormat = res.getString(com.android.internal.R.string.time_date); 1496 } else { 1497 // Example: "Oct 9" 1498 return formatter.format("%s", dateString); 1499 } 1500 } 1501 } else if (showWeekDay) { 1502 if (showTime) { 1503 // Example: "10:00 - 11:00 am, Tue" 1504 fullFormat = res.getString(com.android.internal.R.string.time_wday); 1505 } else { 1506 // Example: "Tue" 1507 return formatter.format("%s", startWeekDayString); 1508 } 1509 } else if (showTime) { 1510 return formatter.format("%s", timeString); 1511 } 1512 1513 // The values that are used in a fullFormat string are specified 1514 // by position. 1515 return formatter.format(fullFormat, timeString, startWeekDayString, dateString); 1516 } 1517 1518 /** 1519 * Formats a date or a time according to the local conventions. There are 1520 * lots of options that allow the caller to control, for example, if the 1521 * time is shown, if the day of the week is shown, if the month name is 1522 * abbreviated, if noon is shown instead of 12pm, and so on. For the 1523 * complete list of options, see the documentation for 1524 * {@link #formatDateRange}. 1525 * <p> 1526 * Example output strings (date formats in these examples are shown using 1527 * the US date format convention but that may change depending on the 1528 * local settings): 1529 * <ul> 1530 * <li>10:15am</li> 1531 * <li>3:00pm</li> 1532 * <li>3pm</li> 1533 * <li>3PM</li> 1534 * <li>08:00</li> 1535 * <li>17:00</li> 1536 * <li>noon</li> 1537 * <li>Noon</li> 1538 * <li>midnight</li> 1539 * <li>Midnight</li> 1540 * <li>Oct 31</li> 1541 * <li>Oct 31, 2007</li> 1542 * <li>October 31, 2007</li> 1543 * <li>10am, Oct 31</li> 1544 * <li>17:00, Oct 31</li> 1545 * <li>Wed</li> 1546 * <li>Wednesday</li> 1547 * <li>10am, Wed, Oct 31</li> 1548 * <li>Wed, Oct 31</li> 1549 * <li>Wednesday, Oct 31</li> 1550 * <li>Wed, Oct 31, 2007</li> 1551 * <li>Wed, October 31</li> 1552 * <li>10/31/2007</li> 1553 * </ul> 1554 * 1555 * @param context the context is required only if the time is shown 1556 * @param millis a point in time in UTC milliseconds 1557 * @param flags a bit mask of formatting options 1558 * @return a string containing the formatted date/time. 1559 */ formatDateTime(Context context, long millis, int flags)1560 public static String formatDateTime(Context context, long millis, int flags) { 1561 return formatDateRange(context, millis, millis, flags); 1562 } 1563 1564 /** 1565 * @return a relative time string to display the time expressed by millis. Times 1566 * are counted starting at midnight, which means that assuming that the current 1567 * time is March 31st, 0:30: 1568 * <ul> 1569 * <li>"millis=0:10 today" will be displayed as "0:10"</li> 1570 * <li>"millis=11:30pm the day before" will be displayed as "Mar 30"</li> 1571 * </ul> 1572 * If the given millis is in a different year, then the full date is 1573 * returned in numeric format (e.g., "10/12/2008"). 1574 * 1575 * @param withPreposition If true, the string returned will include the correct 1576 * preposition ("at 9:20am", "on 10/12/2008" or "on May 29"). 1577 */ getRelativeTimeSpanString(Context c, long millis, boolean withPreposition)1578 public static CharSequence getRelativeTimeSpanString(Context c, long millis, 1579 boolean withPreposition) { 1580 1581 String result; 1582 long now = System.currentTimeMillis(); 1583 long span = Math.abs(now - millis); 1584 1585 synchronized (DateUtils.class) { 1586 if (sNowTime == null) { 1587 sNowTime = new Time(); 1588 } 1589 1590 if (sThenTime == null) { 1591 sThenTime = new Time(); 1592 } 1593 1594 sNowTime.set(now); 1595 sThenTime.set(millis); 1596 1597 int prepositionId; 1598 if (span < DAY_IN_MILLIS && sNowTime.weekDay == sThenTime.weekDay) { 1599 // Same day 1600 int flags = FORMAT_SHOW_TIME; 1601 result = formatDateRange(c, millis, millis, flags); 1602 prepositionId = R.string.preposition_for_time; 1603 } else if (sNowTime.year != sThenTime.year) { 1604 // Different years 1605 int flags = FORMAT_SHOW_DATE | FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE; 1606 result = formatDateRange(c, millis, millis, flags); 1607 1608 // This is a date (like "10/31/2008" so use the date preposition) 1609 prepositionId = R.string.preposition_for_date; 1610 } else { 1611 // Default 1612 int flags = FORMAT_SHOW_DATE | FORMAT_ABBREV_MONTH; 1613 result = formatDateRange(c, millis, millis, flags); 1614 prepositionId = R.string.preposition_for_date; 1615 } 1616 if (withPreposition) { 1617 Resources res = c.getResources(); 1618 result = res.getString(prepositionId, result); 1619 } 1620 } 1621 return result; 1622 } 1623 1624 /** 1625 * Convenience function to return relative time string without preposition. 1626 * @param c context for resources 1627 * @param millis time in milliseconds 1628 * @return {@link CharSequence} containing relative time. 1629 * @see #getRelativeTimeSpanString(Context, long, boolean) 1630 */ getRelativeTimeSpanString(Context c, long millis)1631 public static CharSequence getRelativeTimeSpanString(Context c, long millis) { 1632 return getRelativeTimeSpanString(c, millis, false /* no preposition */); 1633 } 1634 1635 private static Time sNowTime; 1636 private static Time sThenTime; 1637 } 1638