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