Android text to date

SimpleDateFormat

Class Overview

Formats and parses dates in a locale-sensitive manner. Formatting turns a Date into a String , and parsing turns a String into a Date .

Time Pattern Syntax

You can supply a Unicode UTS #35 pattern describing what strings are produced/accepted, but almost all callers should use getDateInstance() , getDateTimeInstance() , or getTimeInstance() to get a ready-made instance suitable for the user’s locale. In cases where the system does not provide a suitable pattern, see getBestDateTimePattern(Locale, String) which lets you specify the elements you’d like in a pattern and get back a pattern suitable for any given locale.

The main reason you’d create an instance this class directly is because you need to format/parse a specific machine-readable format, in which case you almost certainly want to explicitly ask for US to ensure that you get ASCII digits (rather than, say, Arabic digits). (See «Be wary of the default locale».) The most useful non-localized pattern is «yyyy-MM-dd HH:mm:ss.SSSZ» , which corresponds to the ISO 8601 international standard date format.

To specify the time format, use a time pattern string. In this string, any character from ‘A’ to ‘Z’ or ‘a’ to ‘z’ is treated specially. All other characters are passed through verbatim. The interpretation of each of the ASCII letters is given in the table below. ASCII letters not appearing in the table are reserved for future use, and it is an error to attempt to use them.

The number of consecutive copies (the «count») of a pattern character further influences the format, as shown in the table. For fields of kind «number», the count is the minimum number of digits; shorter values are zero-padded to the given width and longer values overflow it.

Symbol Meaning Kind Example
D day in year (Number) 189
E day of week (Text) E / EE / EEE :Tue, EEEE :Tuesday, EEEEE :T
F day of week in month (Number) 2 (2nd Wed in July)
G era designator (Text) AD
H hour in day (0-23) (Number) 0
K hour in am/pm (0-11) (Number) 0
L stand-alone month (Text) L :1 LL :01 LLL :Jan LLLL :January LLLLL :J
M month in year (Text) M :1 MM :01 MMM :Jan MMMM :January MMMMM :J
S fractional seconds (Number) 978
W week in month (Number) 2
Z time zone (RFC 822) (Time Zone) Z / ZZ / ZZZ :-0800 ZZZZ :GMT-08:00 ZZZZZ :-08:00
a am/pm marker (Text) PM
c stand-alone day of week (Text) c / cc / ccc :Tue, cccc :Tuesday, ccccc :T
d day in month (Number) 10
h hour in am/pm (1-12) (Number) 12
k hour in day (1-24) (Number) 24
m minute in hour (Number) 30
s second in minute (Number) 55
w week in year (Number) 27
y year (Number) yy :10 y / yyy / yyyy :2010
z time zone (Time Zone) z / zz / zzz :PST zzzz :Pacific Standard Time
escape for text (Delimiter) ‘Date=’ :Date=
» single quote (Literal) ‘o»clock’ :o’clock

Note that ‘S’ represents fractional seconds and not millisecond values. They will be padded on the left or on the right or both depending on the number of ‘S’ in the pattern. For example, the number of fractional seconds in a Date where Date.getTime() == 1000006 are 0.006 or (6 / 1000) . This leads to the following formatting:

  • «S» => «0»
  • «SSS» => «006»
  • «SSSSSS» => «006000»
Читайте также:  Вложенный список android studio

The two pattern characters L and c are ICU-compatible extensions, not available in the RI or in Android before Android 2.3 (Gingerbread, API level 9). These extensions are necessary for correct localization in languages such as Russian that make a grammatical distinction between, say, the word «June» in the sentence «June» and in the sentence «June 10th»; the former is the stand-alone form, the latter the regular form (because the usual case is to format a complete date). The relationship between E and c is equivalent, but for weekday names.

Five-count patterns (such as «MMMMM») used for the shortest non-numeric representation of a field were introduced in Android 4.3 (Jelly Bean MR2, API level 18).

When two numeric fields are directly adjacent with no intervening delimiter characters, they constitute a run of adjacent numeric fields. Such runs are parsed specially. For example, the format «HHmmss» parses the input text «123456» to 12:34:56, parses the input text «12345» to 1:23:45, and fails to parse «1234». In other words, the leftmost field of the run is flexible, while the others keep a fixed width. If the parse fails anywhere in the run, then the leftmost field is shortened by one character, and the entire run is parsed again. This is repeated until either the parse succeeds or the leftmost field is one character in length. If the parse still fails at that point, the parse of the run fails.

See set2DigitYearStart(Date) for more about handling two-digit years.

Sample Code

If you’re formatting for human use, you should use an instance returned from DateFormat as described above. This 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.

If you’re formatting for machine use, consider this code:

Which produces this output when run in the America/Los_Angeles time zone:

As this example shows, each SimpleDateFormat instance has a TimeZone . This is because it’s called upon to format instances of Date , which represents an absolute time in UTC. That is, Date does not carry time zone information. By default, SimpleDateFormat will use the system’s default time zone. This is appropriate for human-readable output (for which, see the previous sample instead), but generally inappropriate for machine-readable output, where ambiguity is a problem. Note that in this example, the output that included a time but no time zone cannot be parsed back into the original Date . For this reason it is almost always necessary and desirable to include the timezone in the output. It may also be desirable to set the formatter’s time zone to UTC (to ease comparison, or to make logs more readable, for example). It is often best to avoid formatting completely when writing dates/times in machine-readable form. Simply sending the «Unix time» as a long or as the string corresponding to the long is cheaper and unambiguous, and can be formatted any way the recipient deems appropriate.

Читайте также:  Car android player operating manual инструкция

Synchronization

See Also

Summary

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.
calendar The calendar that this DateFormat uses to format a number representing a date.
numberFormat The number format used to format a number.

Public Constructors

public SimpleDateFormat ()

Constructs a new SimpleDateFormat for formatting and parsing dates and times in the SHORT style for the user’s default locale. See «Be wary of the default locale».

public SimpleDateFormat (String pattern)

Constructs a new SimpleDateFormat using the specified non-localized pattern and the DateFormatSymbols and Calendar for the user’s default locale. See «Be wary of the default locale».

Источник

Android text to date

Android FixDate EditText

This library simplified the way of get date from user input, Allows the user to enter a date as a text and then verify it based on date format, divider character and min or max date with other options.

1- Define new DateEdit text inside you layout xml

2- start listening to user input from your acticity, fragment or any android UI components

Читайте также:  Калькулятор для планшета андроид

and just that’s it!

please download the sample and watch the video to dive more deep.

  • You can choose between two format «ddMMyyyy» or «MMyy» maybe in the future i will add more, you can add and then make pull request.
  • You can choose between two divider Character «/» or «-«.
  • Set the max date which can user enter it as a string from xml and as a Date object from the code.
  • Set the min date which can user enter it as a string from xml and as a Date object from the code.
  • If you want to show error alert to user if he enters something invalid set autoCorrect = false, if you want autocorrecting to what the user inputing set it to «true».
  • Show helper text, Used just with TextInputLayout.
  • Highlighted helper text color for what user inputed.

Источник

Как вы форматируете дату и время в 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 – это формат, который вам нужен

Источник

Оцените статью