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