- Zheka’s blog
- Monday, July 1, 2013
- Форматирование даты/времени в Android приложении
- DateUtils
- Class Overview
- Summary
- Constants
- public static final String ABBREV_MONTH_FORMAT
- 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
- public static final long HOUR_IN_MILLIS
- public static final String HOUR_MINUTE_24
- public static final int LENGTH_LONG
- public static final int LENGTH_MEDIUM
- public static final int LENGTH_SHORT
- public static final int LENGTH_SHORTER
- public static final int LENGTH_SHORTEST
- 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
- Fields
- public static final int[] sameMonthTable
- public static final int[] sameYearTable
- Public Constructors
- public DateUtils ()
- Public Methods
- 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). Если добавить миллисекунды, то диапазон будет представлен верно.
Чтобы ваше приложение правильно представляло дату/время и по прежнему имело возможность контролировать формат 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 | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
Constantspublic static final String ABBREV_MONTH_FORMATThis constant was deprecated in API level 17. This is not actually a useful month name in all locales. public static final String ABBREV_WEEKDAY_FORMATpublic static final long DAY_IN_MILLISpublic static final int FORMAT_12HOURpublic static final int FORMAT_24HOURpublic static final int FORMAT_ABBREV_ALLpublic static final int FORMAT_ABBREV_MONTHpublic static final int FORMAT_ABBREV_RELATIVEpublic static final int FORMAT_ABBREV_TIMEpublic static final int FORMAT_ABBREV_WEEKDAYpublic static final int FORMAT_CAP_AMPMpublic static final int FORMAT_CAP_MIDNIGHTpublic static final int FORMAT_CAP_NOONpublic static final int FORMAT_CAP_NOON_MIDNIGHTpublic static final int FORMAT_NO_MIDNIGHTpublic static final int FORMAT_NO_MONTH_DAYpublic static final int FORMAT_NO_NOONpublic static final int FORMAT_NO_NOON_MIDNIGHTpublic static final int FORMAT_NO_YEARpublic static final int FORMAT_NUMERIC_DATEpublic static final int FORMAT_SHOW_DATEpublic static final int FORMAT_SHOW_TIMEpublic static final int FORMAT_SHOW_WEEKDAYpublic static final int FORMAT_SHOW_YEARpublic static final int FORMAT_UTCThis constant was deprecated in API level 9. public static final long HOUR_IN_MILLISpublic static final String HOUR_MINUTE_24This constant was deprecated in API level 17. This is not actually the preferred 24-hour date format in all locales. public static final int LENGTH_LONGThis constant was deprecated in API level 17. 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_MEDIUMThis constant was deprecated in API level 17. 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_SHORTThis constant was deprecated in API level 17. 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_SHORTERThis constant was deprecated in API level 17. 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_SHORTESTThis constant was deprecated in API level 17. 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_MILLISpublic static final String MONTH_DAY_FORMATpublic static final String MONTH_FORMATpublic static final String NUMERIC_MONTH_FORMATpublic static final long SECOND_IN_MILLISpublic static final String WEEKDAY_FORMATpublic static final long WEEK_IN_MILLISpublic static final String YEAR_FORMATpublic static final String YEAR_FORMAT_TWO_DIGITSpublic static final long YEAR_IN_MILLISThis constant is actually the length of 364 days, not of a year! Fieldspublic static final int[] sameMonthTableThis field was deprecated in API level 17. public static final int[] sameYearTableThis field was deprecated in API level 17. Public Constructorspublic DateUtils ()Public Methodspublic 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):
The flags argument is a bitmask of options from the following list:
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:
Источник |