Одним из аспектов локализации приложения является представление времени и даты в соответствии с настройками устройства. Различные страны/регионы используют разные форматы, как следствие, нужно учитывать ряд моментов.
Первая мысль, которая приходит в голову — это использование 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 — хорошая отправная точка. Зная и умело используя флаги, можно добиться определенной гибкости.
Источник
Как вы форматируете дату и время в Android?
Как вы правильно отформатируете в соответствии с конфигурацией устройства дату и время, когда у вас есть год, месяц, день, час и минута?
Используйте стандартный класс Java DateFormat.
Например, чтобы отобразить текущую дату и время, выполните следующие действия:
Вы можете инициализировать объект Date своими собственными значениями, однако вы должны знать, что конструкторы устарели, и вы действительно должны использовать объект Java Calendar.
На мой взгляд, android.text.format.DateFormat.getDateFormat(context) меня смущает, потому что этот метод возвращает java.text.DateFormat а не android.text.format.DateFormat – – «.
Итак, я использую код фрагмента, как показано ниже, чтобы получить текущую дату / время в моем формате.
Кроме того, вы можете использовать другие форматы. Следуйте за DateFormat .
Дата для строки даты локали:
-> 31 декабря 1969 года
-> 31 декабря 1969 года 16:00:00
Это сделает это:
Использовать SimpleDateFormat
Лучше использовать родной язык Android. Класс времени:
Это мой метод, вы можете определять и вводить и выводить формат.
Используйте сборку в классе времени!
SimpleDateFormat
Я использую SimpleDateFormat без настраиваемого шаблона, чтобы получить фактическую дату и время из системы в предварительно выбранном формате устройства:
Возвращает :
Используйте эти два как переменные класса:
И используйте его вот так:
Этот код вернет текущую дату и время:
И когда вы получаете доступ к переданным переменным:
Я использую его так:
Избегайте juDate
Java.util.Date и .Calendar и SimpleDateFormat на Java (и Android), как известно, являются неприятными. Избежать их. Они настолько плохи, что Sun / Oracle отказались от них, вытеснив их новым пакетом java.time в Java 8 (не в Android от 2014 года). Новый java.time был вдохновлен библиотекой Joda-Time .
Joda времени
Joda-Time работает в Android.
Найдите StackOverflow для «Joda», чтобы найти много примеров и много дискуссий.
Это лакомый кусок исходного кода с использованием Joda-Time 2.4.
Вернуться к 2016, Когда я хочу настроить формат (не в соответствии с конфигурацией устройства, как вы просите …) Обычно я использую файл строкового ресурса:
Это также полезно при выпуске новой библиотеки привязки даты .
Поэтому я могу иметь что-то подобное в файле макета:
И в классе java:
Вот как я это сделал:
Надеюсь, это полезно 🙂
Слишком поздно, но это может помочь кому-то
Здесь format – это формат, который вам нужен
Источник
DateFormat
java.lang.Object
↳
java.text.Format
↳
java.text.DateFormat
Known Direct Subclasses
SimpleDateFormat
Formats and parses dates in a locale-sensitive manner.
Class Overview
Formats or parses dates and times.
This class provides factories for obtaining instances configured for a specific locale. The most common subclass is SimpleDateFormat .
Sample Code
Produces this output when run on an en_US device in the America/Los_Angeles time zone: And will produce similarly appropriate localized human-readable output on any user’s system. Notice how the same point in time when formatted can appear to be a different time when rendered for a different time zone. This is one reason why formatting should be left until the data will only be presented to a human. Machines should interchange «Unix time» integers.
Summary
Nested Classes
DateFormat.Field
The instances of this inner class are used as attribute keys and values in AttributedCharacterIterator that the formatToCharacterIterator(Object) method returns.
Constants
int
AM_PM_FIELD
FieldPosition selector for ‘a’ field alignment, corresponds to the AM_PM field.
int
DATE_FIELD
The FieldPosition selector for ‘d’ field alignment, corresponds to the DATE field.
int
DAY_OF_WEEK_FIELD
FieldPosition selector for ‘E’ field alignment, corresponds to the DAY_OF_WEEK field.
int
DAY_OF_WEEK_IN_MONTH_FIELD
FieldPosition selector for ‘F’ field alignment, corresponds to the DAY_OF_WEEK_IN_MONTH field.
int
DAY_OF_YEAR_FIELD
FieldPosition selector for ‘D’ field alignment, corresponds to the DAY_OF_YEAR field.
int
DEFAULT
The format style constant defining the default format style.
int
ERA_FIELD
The FieldPosition selector for ‘G’ field alignment, corresponds to the ERA field.
int
FULL
The format style constant defining the full style.
int
HOUR0_FIELD
The FieldPosition selector for ‘K’ field alignment, corresponding to the HOUR field.
int
HOUR1_FIELD
FieldPosition selector for ‘h’ field alignment, corresponding to the HOUR field.
int
HOUR_OF_DAY0_FIELD
The FieldPosition selector for ‘H’ field alignment, corresponds to the HOUR_OF_DAY field.
int
HOUR_OF_DAY1_FIELD
The FieldPosition selector for ‘k’ field alignment, corresponds to the HOUR_OF_DAY field.
int
LONG
The format style constant defining the long style.
int
MEDIUM
The format style constant defining the medium style.
int
MILLISECOND_FIELD
FieldPosition selector for ‘S’ field alignment, corresponds to the MILLISECOND field.
int
MINUTE_FIELD
FieldPosition selector for ‘m’ field alignment, corresponds to the MINUTE field.
int
MONTH_FIELD
The FieldPosition selector for ‘M’ field alignment, corresponds to the MONTH field.
int
SECOND_FIELD
FieldPosition selector for ‘s’ field alignment, corresponds to the SECOND field.
int
SHORT
The format style constant defining the short style.
int
TIMEZONE_FIELD
The FieldPosition selector for ‘z’ field alignment, corresponds to the ZONE_OFFSET and DST_OFFSET fields.
int
WEEK_OF_MONTH_FIELD
FieldPosition selector for ‘W’ field alignment, corresponds to the WEEK_OF_MONTH field.
int
WEEK_OF_YEAR_FIELD
FieldPosition selector for ‘w’ field alignment, corresponds to the WEEK_OF_YEAR field.
int
YEAR_FIELD
The FieldPosition selector for ‘y’ field alignment, corresponds to the YEAR field.
Fields
calendar
The calendar that this DateFormat uses to format a number representing a date.
numberFormat
The number format used to format a number.
Protected Constructors
Constants
public static final int AM_PM_FIELD
FieldPosition selector for ‘a’ field alignment, corresponds to the AM_PM field.
public static final int DATE_FIELD
The FieldPosition selector for ‘d’ field alignment, corresponds to the DATE field.
public static final int DAY_OF_WEEK_FIELD
FieldPosition selector for ‘E’ field alignment, corresponds to the DAY_OF_WEEK field.
public static final int DAY_OF_WEEK_IN_MONTH_FIELD
FieldPosition selector for ‘F’ field alignment, corresponds to the DAY_OF_WEEK_IN_MONTH field.
public static final int DAY_OF_YEAR_FIELD
FieldPosition selector for ‘D’ field alignment, corresponds to the DAY_OF_YEAR field.
public static final int DEFAULT
The format style constant defining the default format style. The default is MEDIUM.
public static final int ERA_FIELD
The FieldPosition selector for ‘G’ field alignment, corresponds to the ERA field.
public static final int FULL
The format style constant defining the full style.
public static final int HOUR0_FIELD
The FieldPosition selector for ‘K’ field alignment, corresponding to the HOUR field.
public static final int HOUR1_FIELD
FieldPosition selector for ‘h’ field alignment, corresponding to the HOUR field.
public static final int HOUR_OF_DAY0_FIELD
The FieldPosition selector for ‘H’ field alignment, corresponds to the HOUR_OF_DAY field. HOUR_OF_DAY0_FIELD is used for the zero-based 24-hour clock. For example, 23:59 + 01:00 results in 00:59.
public static final int HOUR_OF_DAY1_FIELD
The FieldPosition selector for ‘k’ field alignment, corresponds to the HOUR_OF_DAY field. HOUR_OF_DAY1_FIELD is used for the one-based 24-hour clock. For example, 23:59 + 01:00 results in 24:59.
public static final int LONG
The format style constant defining the long style.
public static final int MEDIUM
The format style constant defining the medium style.
public static final int MILLISECOND_FIELD
FieldPosition selector for ‘S’ field alignment, corresponds to the MILLISECOND field.
public static final int MINUTE_FIELD
FieldPosition selector for ‘m’ field alignment, corresponds to the MINUTE field.
public static final int MONTH_FIELD
The FieldPosition selector for ‘M’ field alignment, corresponds to the MONTH field.
public static final int SECOND_FIELD
FieldPosition selector for ‘s’ field alignment, corresponds to the SECOND field.
public static final int SHORT
The format style constant defining the short style.
public static final int TIMEZONE_FIELD
The FieldPosition selector for ‘z’ field alignment, corresponds to the ZONE_OFFSET and DST_OFFSET fields.
public static final int WEEK_OF_MONTH_FIELD
FieldPosition selector for ‘W’ field alignment, corresponds to the WEEK_OF_MONTH field.
public static final int WEEK_OF_YEAR_FIELD
FieldPosition selector for ‘w’ field alignment, corresponds to the WEEK_OF_YEAR field.
public static final int YEAR_FIELD
The FieldPosition selector for ‘y’ field alignment, corresponds to the YEAR field.
Fields
protected Calendar calendar
The calendar that this DateFormat uses to format a number representing a date.
Источник
DateFormat
Class Overview
Utility class for producing strings with formatted date/time.
Most callers should avoid supplying their own format strings to this class’ format methods and rely on the correctly localized ones supplied by the system. This class’ factory methods return appropriately-localized DateFormat instances, suitable for both formatting and parsing dates. For the canonical documentation of format strings, see SimpleDateFormat .
The format methods in this class takes as inputs a format string and a representation of a date/time. The format string controls how the output is generated. This class only supports a subset of the full Unicode specification. Use SimpleDateFormat if you need more. Formatting characters may be repeated in order to get more detailed representations of that field. For instance, the format character ‘M’ is used to represent the month. Depending on how many times that character is repeated you get a different representation.
For the month of September: M -> 9 MM -> 09 MMM -> Sep MMMM -> September
The effects of the duplication vary depending on the nature of the field. See the notes on the individual field formatters for details. For purely numeric fields such as HOUR adding more copies of the designator will zero-pad the value to that number of characters.
For 7 minutes past the hour: m -> 7 mm -> 07 mmm -> 007 mmmm -> 0007
This designator indicates whether the HOUR field is before or after noon.
char
CAPITAL_AM_PM
This designator indicates whether the HOUR field is before or after noon.
char
DATE
This designator indicates the day of the month.
char
DAY
This designator indicates the name of the day of the week.
char
HOUR
This designator indicates the hour of the day in 12 hour format.
char
HOUR_OF_DAY
This designator indicates the hour of the day in 24 hour format.
char
MINUTE
This designator indicates the minute of the hour.
char
MONTH
This designator indicates the month of the year.
char
QUOTE
Text in the format string that should be copied verbatim rather that interpreted as formatting codes must be surrounded by the QUOTE character.
char
SECONDS
This designator indicates the seconds of the minute.
char
STANDALONE_MONTH
This designator indicates the standalone month of the year, necessary in some format strings in some languages.
char
TIME_ZONE
This designator indicates the offset of the timezone from GMT.
char
YEAR
This designator indicates the year.
Public Constructors
Public Methods
Constants
public static final char AM_PM
This designator indicates whether the HOUR field is before or after noon. The output is lower-case. Examples: a -> a or p aa -> am or pm
public static final char CAPITAL_AM_PM
This designator indicates whether the HOUR field is before or after noon. The output is capitalized. Examples: A -> A or P AA -> AM or PM
public static final char DATE
This designator indicates the day of the month. Examples for the 9th of the month: d -> 9 dd -> 09
public static final char DAY
This designator indicates the name of the day of the week. Examples for Sunday: E -> Sun EEEE -> Sunday
public static final char HOUR
This designator indicates the hour of the day in 12 hour format. Examples for 3pm: h -> 3 hh -> 03
public static final char HOUR_OF_DAY
This designator indicates the hour of the day in 24 hour format. Example for 3pm: k -> 15 Examples for midnight: k -> 0 kk -> 00
public static final char MINUTE
This designator indicates the minute of the hour. Examples for 7 minutes past the hour: m -> 7 mm -> 07
public static final char MONTH
This designator indicates the month of the year. See also STANDALONE_MONTH . Examples for September: M -> 9 MM -> 09 MMM -> Sep MMMM -> September
public static final char QUOTE
Text in the format string that should be copied verbatim rather that interpreted as formatting codes must be surrounded by the QUOTE character. If you need to embed a literal QUOTE character in the output text then use two in a row.
public static final char SECONDS
This designator indicates the seconds of the minute. Examples for 7 seconds past the minute: s -> 7 ss -> 07
public static final char STANDALONE_MONTH
This designator indicates the standalone month of the year, necessary in some format strings in some languages. For example, Russian distinguishes between the «June» in «June» and that in «June 2010».
public static final char TIME_ZONE
This designator indicates the offset of the timezone from GMT. Example for US/Pacific timezone: z -> -0800 zz -> PST
public static final char YEAR
This designator indicates the year. Examples for 2006 y -> 06 yyyy -> 2006