Android studio dateutils formatdatetime

Содержание
  1. Zheka’s blog
  2. Monday, July 1, 2013
  3. Форматирование даты/времени в Android приложении
  4. DateUtils
  5. Class Overview
  6. Summary
  7. Constants
  8. public static final String ABBREV_MONTH_FORMAT
  9. public static final String ABBREV_WEEKDAY_FORMAT
  10. public static final long DAY_IN_MILLIS
  11. public static final int FORMAT_12HOUR
  12. public static final int FORMAT_24HOUR
  13. public static final int FORMAT_ABBREV_ALL
  14. public static final int FORMAT_ABBREV_MONTH
  15. public static final int FORMAT_ABBREV_RELATIVE
  16. public static final int FORMAT_ABBREV_TIME
  17. public static final int FORMAT_ABBREV_WEEKDAY
  18. public static final int FORMAT_CAP_AMPM
  19. public static final int FORMAT_CAP_MIDNIGHT
  20. public static final int FORMAT_CAP_NOON
  21. public static final int FORMAT_CAP_NOON_MIDNIGHT
  22. public static final int FORMAT_NO_MIDNIGHT
  23. public static final int FORMAT_NO_MONTH_DAY
  24. public static final int FORMAT_NO_NOON
  25. public static final int FORMAT_NO_NOON_MIDNIGHT
  26. public static final int FORMAT_NO_YEAR
  27. public static final int FORMAT_NUMERIC_DATE
  28. public static final int FORMAT_SHOW_DATE
  29. public static final int FORMAT_SHOW_TIME
  30. public static final int FORMAT_SHOW_WEEKDAY
  31. public static final int FORMAT_SHOW_YEAR
  32. public static final int FORMAT_UTC
  33. public static final long HOUR_IN_MILLIS
  34. public static final String HOUR_MINUTE_24
  35. public static final int LENGTH_LONG
  36. public static final int LENGTH_MEDIUM
  37. public static final int LENGTH_SHORT
  38. public static final int LENGTH_SHORTER
  39. public static final int LENGTH_SHORTEST
  40. public static final long MINUTE_IN_MILLIS
  41. public static final String MONTH_DAY_FORMAT
  42. public static final String MONTH_FORMAT
  43. public static final String NUMERIC_MONTH_FORMAT
  44. public static final long SECOND_IN_MILLIS
  45. public static final String WEEKDAY_FORMAT
  46. public static final long WEEK_IN_MILLIS
  47. public static final String YEAR_FORMAT
  48. public static final String YEAR_FORMAT_TWO_DIGITS
  49. public static final long YEAR_IN_MILLIS
  50. Fields
  51. public static final int[] sameMonthTable
  52. public static final int[] sameYearTable
  53. Public Constructors
  54. public DateUtils ()
  55. Public Methods
  56. public static Formatter formatDateRange (Context context, Formatter formatter, long startMillis, long endMillis, int flags, String timeZone)

Zheka’s blog

Monday, July 1, 2013

Форматирование даты/времени в Android приложении

Одним из аспектов локализации приложения является представление времени и даты в соответствии с настройками устройства. Различные страны/регионы используют разные форматы, как следствие, нужно учитывать ряд моментов.

Первая мысль, которая приходит в голову — это использование java.text.DateFormat (и как частный случай SimpleDateFormat ):

Данный подход хорошо работает, скажем, для вэб сервиса, но он совсем неприемлем для мобильных приложений. Т.к. с большой долей вероятности для конечного пользователя шаблон форматирования не является привычным. Например, не ясно когда часы(суточное время) должны быть представлены в 12-и или 24-х часовом формате.

Более правильный решение — это использовать android.text.format.DateFormat . Класс имеет ряд методов, возвращающих шаблон представления даты/времени в соответствии с системной локалью: getDateFormat() , getTimeFormat() и т.д.

Недостаток — это полное отсутствие гибкости. Скажем, что если я не хочу показывать год или наоборот — добавить день недели? Как можно догадаться, применять такое форматирование можно лишь в частном случае, когда нет жестких требований.

Мы подошли вплотную к правильному решению — DateUtils . Класс предоставляет семейство методов formatDateTime() и formatDateRange , принимающие флаги в качестве параметров, указывающие, какие поля нужно включить в шаблон. Преимущество в том, что форматирование осуществляется автоматически с учетом локали пользователя, избавляя нас от обработки всех тонкостей вручную:

DateUtils.formatDateRange() необходим для форматирования временного диапазона(например, «Jan 5 — Feb 12» ). Может возникнуть логичный вопрос. Для чего это нужно, если можно выполнить конкатенацию двух дат с использованием formatDateTime() ? Помимо того что он проще, в опр. условиях будет выполнена оптимизация представления даты за счет уменьшения количества отображаемых полей(например, если год/месяц не меняется в рамках диапазона):

Единственная вещь в formatDateRange() на которую следует обратить внимание — округления даты. Возможно вы заметили в примере выше, что верхняя граница диапазона была округлена в меньшую сторону(до 24 декабря вместо 25-го). Это произошло из-за того, что было выполнено отсечение по суточной границе(оригинальный текст — that’s because it cuts off at midnight). Если добавить миллисекунды, то диапазон будет представлен верно.

Читайте также:  Заводской пароль для сброса настроек android

Чтобы ваше приложение правильно представляло дату/время и по прежнему имело возможность контролировать формат DateUtils — хорошая отправная точка. Зная и умело используя флаги, можно добиться определенной гибкости.

Источник

DateUtils

Class Overview

This class contains various date-related utilities for creating text for things like elapsed time and date ranges, strings for days of the week and months, and AM/PM text etc.

Summary

Constants
String ABBREV_MONTH_FORMAT This constant was deprecated in API level 17. use SimpleDateFormat instead.
String ABBREV_WEEKDAY_FORMAT
long DAY_IN_MILLIS
int FORMAT_12HOUR
int FORMAT_24HOUR
int FORMAT_ABBREV_ALL
int FORMAT_ABBREV_MONTH
int FORMAT_ABBREV_RELATIVE
int FORMAT_ABBREV_TIME
int FORMAT_ABBREV_WEEKDAY
int FORMAT_CAP_AMPM
int FORMAT_CAP_MIDNIGHT
int FORMAT_CAP_NOON
int FORMAT_CAP_NOON_MIDNIGHT
int FORMAT_NO_MIDNIGHT
int FORMAT_NO_MONTH_DAY
int FORMAT_NO_NOON
int FORMAT_NO_NOON_MIDNIGHT
int FORMAT_NO_YEAR
int FORMAT_NUMERIC_DATE
int FORMAT_SHOW_DATE
int FORMAT_SHOW_TIME
int FORMAT_SHOW_WEEKDAY
int FORMAT_SHOW_YEAR
int FORMAT_UTC This constant was deprecated in API level 9. Use formatDateRange and pass in Time.TIMEZONE_UTC for the timeZone instead.
long HOUR_IN_MILLIS
String HOUR_MINUTE_24 This constant was deprecated in API level 17. use SimpleDateFormat instead.
int LENGTH_LONG This constant was deprecated in API level 17. use SimpleDateFormat instead.
int LENGTH_MEDIUM This constant was deprecated in API level 17. use SimpleDateFormat instead.
int LENGTH_SHORT This constant was deprecated in API level 17. use SimpleDateFormat instead.
int LENGTH_SHORTER This constant was deprecated in API level 17. use SimpleDateFormat instead.
int LENGTH_SHORTEST This constant was deprecated in API level 17. use SimpleDateFormat instead.
long MINUTE_IN_MILLIS
String MONTH_DAY_FORMAT
String MONTH_FORMAT
String NUMERIC_MONTH_FORMAT
long SECOND_IN_MILLIS
String WEEKDAY_FORMAT
long WEEK_IN_MILLIS
String YEAR_FORMAT
String YEAR_FORMAT_TWO_DIGITS
long YEAR_IN_MILLIS This constant is actually the length of 364 days, not of a year!
Fields
sameMonthTable This field was deprecated in API level 17. do not use.
sameYearTable This field was deprecated in API level 17. do not use.
Public Constructors
Public Methods

Constants

public static final String ABBREV_MONTH_FORMAT

This constant was deprecated in API level 17.
use SimpleDateFormat instead.

This is not actually a useful month name in all locales.

public static final String ABBREV_WEEKDAY_FORMAT

public static final long DAY_IN_MILLIS

public static final int FORMAT_12HOUR

public static final int FORMAT_24HOUR

public static final int FORMAT_ABBREV_ALL

public static final int FORMAT_ABBREV_MONTH

public static final int FORMAT_ABBREV_RELATIVE

public static final int FORMAT_ABBREV_TIME

public static final int FORMAT_ABBREV_WEEKDAY

public static final int FORMAT_CAP_AMPM

public static final int FORMAT_CAP_MIDNIGHT

public static final int FORMAT_CAP_NOON

public static final int FORMAT_CAP_NOON_MIDNIGHT

public static final int FORMAT_NO_MIDNIGHT

public static final int FORMAT_NO_MONTH_DAY

public static final int FORMAT_NO_NOON

public static final int FORMAT_NO_NOON_MIDNIGHT

public static final int FORMAT_NO_YEAR

public static final int FORMAT_NUMERIC_DATE

public static final int FORMAT_SHOW_DATE

public static final int FORMAT_SHOW_TIME

public static final int FORMAT_SHOW_WEEKDAY

public static final int FORMAT_SHOW_YEAR

public static final int FORMAT_UTC

This constant was deprecated in API level 9.
Use formatDateRange and pass in Time.TIMEZONE_UTC for the timeZone instead.

public static final long HOUR_IN_MILLIS

public static final String HOUR_MINUTE_24

This constant was deprecated in API level 17.
use SimpleDateFormat instead.

This is not actually the preferred 24-hour date format in all locales.

public static final int LENGTH_LONG

This constant was deprecated in API level 17.
use SimpleDateFormat instead.

Request the full spelled-out name. For use with the ‘abbrev’ parameter of getDayOfWeekString(int, int) and getMonthString(int, int) .

public static final int LENGTH_MEDIUM

This constant was deprecated in API level 17.
use SimpleDateFormat instead.

Request an abbreviated version of the name. For use with the ‘abbrev’ parameter of getDayOfWeekString(int, int) and getMonthString(int, int) .

public static final int LENGTH_SHORT

This constant was deprecated in API level 17.
use SimpleDateFormat instead.

Request a shorter abbreviated version of the name. For use with the ‘abbrev’ parameter of getDayOfWeekString(int, int) and getMonthString(int, int) .

public static final int LENGTH_SHORTER

This constant was deprecated in API level 17.
use SimpleDateFormat instead.

Request an even shorter abbreviated version of the name. Do not use this. Currently this will always return the same result as LENGTH_SHORT .

public static final int LENGTH_SHORTEST

This constant was deprecated in API level 17.
use SimpleDateFormat instead.

Request an even shorter abbreviated version of the name. For use with the ‘abbrev’ parameter of getDayOfWeekString(int, int) and getMonthString(int, int) .

public static final long MINUTE_IN_MILLIS

public static final String MONTH_DAY_FORMAT

public static final String MONTH_FORMAT

public static final String NUMERIC_MONTH_FORMAT

public static final long SECOND_IN_MILLIS

public static final String WEEKDAY_FORMAT

public static final long WEEK_IN_MILLIS

public static final String YEAR_FORMAT

public static final String YEAR_FORMAT_TWO_DIGITS

public static final long YEAR_IN_MILLIS

This constant is actually the length of 364 days, not of a year!

Fields

public static final int[] sameMonthTable

This field was deprecated in API level 17.
do not use.

public static final int[] sameYearTable

This field was deprecated in API level 17.
do not use.

Public Constructors

public DateUtils ()

Public Methods

public static Formatter formatDateRange (Context context, Formatter formatter, long startMillis, long endMillis, int flags, String timeZone)

Formats a date or a time range according to the local conventions.

Example output strings (date formats in these examples are shown using the US date format convention but that may change depending on the local settings):

  • 10:15am
  • 3:00pm — 4:00pm
  • 3pm — 4pm
  • 3PM — 4PM
  • 08:00 — 17:00
  • Oct 9
  • Tue, Oct 9
  • October 9, 2007
  • Oct 9 — 10
  • Oct 9 — 10, 2007
  • Oct 28 — Nov 3, 2007
  • Dec 31, 2007 — Jan 1, 2008
  • Oct 9, 8:00am — Oct 10, 5:00pm
  • 12/31/2007 — 01/01/2008

The flags argument is a bitmask of options from the following list:

  • FORMAT_SHOW_TIME
  • FORMAT_SHOW_WEEKDAY
  • FORMAT_SHOW_YEAR
  • FORMAT_NO_YEAR
  • FORMAT_SHOW_DATE
  • FORMAT_NO_MONTH_DAY
  • FORMAT_12HOUR
  • FORMAT_24HOUR
  • FORMAT_CAP_AMPM
  • FORMAT_NO_NOON
  • FORMAT_CAP_NOON
  • FORMAT_NO_MIDNIGHT
  • FORMAT_CAP_MIDNIGHT
  • FORMAT_UTC
  • FORMAT_ABBREV_TIME
  • FORMAT_ABBREV_WEEKDAY
  • FORMAT_ABBREV_MONTH
  • FORMAT_ABBREV_ALL
  • FORMAT_NUMERIC_DATE

If FORMAT_SHOW_TIME is set, the time is shown as part of the date range. If the start and end time are the same, then just the start time is shown.

If FORMAT_SHOW_WEEKDAY is set, then the weekday is shown.

If FORMAT_SHOW_YEAR is set, then the year is always shown. If FORMAT_NO_YEAR is set, then the year is not shown. If neither FORMAT_SHOW_YEAR nor FORMAT_NO_YEAR are set, then the year is shown only if it is different from the current year, or if the start and end dates fall on different years. If both are set, FORMAT_SHOW_YEAR takes precedence.

Normally the date is shown unless the start and end day are the same. If FORMAT_SHOW_DATE is set, then the date is always shown, even for same day ranges.

If FORMAT_NO_MONTH_DAY is set, then if the date is shown, just the month name will be shown, not the day of the month. For example, «January, 2008» instead of «January 6 — 12, 2008».

If FORMAT_CAP_AMPM is set and 12-hour time is used, then the «AM» and «PM» are capitalized. You should not use this flag because in some locales these terms cannot be capitalized, and in many others it doesn’t make sense to do so even though it is possible.

If FORMAT_NO_NOON is set and 12-hour time is used, then «12pm» is shown instead of «noon».

If FORMAT_CAP_NOON is set and 12-hour time is used, then «Noon» is shown instead of «noon». You should probably not use this flag because in many locales it will not make sense to capitalize the term.

If FORMAT_NO_MIDNIGHT is set and 12-hour time is used, then «12am» is shown instead of «midnight».

If FORMAT_CAP_MIDNIGHT is set and 12-hour time is used, then «Midnight» is shown instead of «midnight». You should probably not use this flag because in many locales it will not make sense to capitalize the term.

If FORMAT_12HOUR is set and the time is shown, then the time is shown in the 12-hour time format. You should not normally set this. Instead, let the time format be chosen automatically according to the system settings. If both FORMAT_12HOUR and FORMAT_24HOUR are set, then FORMAT_24HOUR takes precedence.

If FORMAT_24HOUR is set and the time is shown, then the time is shown in the 24-hour time format. You should not normally set this. Instead, let the time format be chosen automatically according to the system settings. If both FORMAT_12HOUR and FORMAT_24HOUR are set, then FORMAT_24HOUR takes precedence.

If FORMAT_UTC is set, then the UTC time zone is used for the start and end milliseconds unless a time zone is specified. If a time zone is specified it will be used regardless of the FORMAT_UTC flag.

If FORMAT_ABBREV_TIME is set and 12-hour time format is used, then the start and end times (if shown) are abbreviated by not showing the minutes if they are zero. For example, instead of «3:00pm» the time would be abbreviated to «3pm».

If FORMAT_ABBREV_WEEKDAY is set, then the weekday (if shown) is abbreviated to a 3-letter string.

If FORMAT_ABBREV_MONTH is set, then the month (if shown) is abbreviated to a 3-letter string.

If FORMAT_ABBREV_ALL is set, then the weekday and the month (if shown) are abbreviated to 3-letter strings.

If FORMAT_NUMERIC_DATE is set, then the date is shown in numeric format instead of using the name of the month. For example, «12/31/2008» instead of «December 31, 2008».

If the end date ends at 12:00am at the beginning of a day, it is formatted as the end of the previous day in two scenarios:

  • For single day events. This results in «8pm — midnight» instead of «Nov 10, 8pm — Nov 11, 12am».
  • When the time is not displayed. This results in «Nov 10 — 11» for an event with a start date of Nov 10 and an end date of Nov 12 at 00:00.

Источник

Читайте также:  Принтер совместимый с андроид устройством
Оцените статью