- Форматирование даты в Java с помощью SimpleDateFormat
- Simpledateformat android studio примеры
- Date and Time Patterns
- Examples
- Synchronization
- SimpleDateFormat
- Class Overview
- Time Pattern Syntax
- Sample Code
- Synchronization
- Summary
- Public Constructors
- public SimpleDateFormat ()
- public SimpleDateFormat (String pattern)
Форматирование даты в Java с помощью SimpleDateFormat
Для форматирования ввода и вывода даты в Java до введения нового Date Time API (https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html), который был введен в Java 8, использовался класс SimpleDateFormat.
SimpleDateFormat является подклассом DateFormat, который позволяет форматировать ввод-вывод даты и времени в рамках предопределенных стилей. В отличие от DateFormat, SimpleDateFormat позволяет создавать собственные настраиваемые форматы ввода-вывода.
Для создания экземпляра класса SimpleDateFormat используется один из 4 конструкторов:
- SimpleDateFormat()
- SimpleDateFormat(String pattern)
- SimpleDateFormat(String pattern, DateFormatSymbols formatSymbols)
- SimpleDateFormat(String pattern, Locale locale)
pattern – шаблон определяющий формат даты и времени
formatSymbols – символы формата даты (например название месяцев или дней недели)
locale — локаль
SimpleDateFormat чувствителен к локали. При создании экземпляра SimpleDateFormat без параметра Locale, вывод будет форматироваться в соответствии с Locale по умолчанию.
Синтаксис шаблона форматирования даты
Символ | Значение | Представление | Пример |
G | обозначение эры | Текст | AD, н.э. |
y или yyyy | год (4 цифры) | Число | 2017 |
yy | год (2 последние цифры) | Число | 17 |
M | номер месяца без лидирующих нулей | Число | 1, 11 |
MM | номер месяца дополненный нулями | Число | 01, 11 |
MMM | сокращенное название месяца | Текст | дек, Dec |
MMMM | полное название месяца (контекстно-зависимое) | Текст | декабря, December |
LLLL | полное название месяца (контекстно-независимое) | Текст | Декабрь, December |
w | неделя в году | Число | 13 |
W | неделя в месяце | Число | 3 |
D | день в году | Число | 172 |
d | день месяца | Число | 11 |
F | день недели в месяце | Число | 1 |
E | сокращенное название дня недели | Текст | Ср, Wed |
EEEE | полное название дня недели | Текст | среда, Wednesday |
u | номер дня недели (1-пн .. 7-вск) | Число | 3 |
a | маркер am/pm | Текст | AM |
H | Час в дне (0-23) | Число | 0 |
h | Часы в am/pm (1-12) | Число | 12 |
K | час в am/pm (0-11) | Число | 0 |
k | час в дне (1-24) | Число | 24 |
m | минута в часе | Число | 18 |
s | секунда в минуте | Число | 35 |
S | миллисекунды | Число | 978 |
z | часовой пояс | Текст | GMT+07:00 |
Z | часовой пояс в формате RFC 822 | Текст | 700 |
X | часовой пояс в формате ISO 8601 | Текст | 7 |
Символы, не являющиеся буквами обрабатываются как текст в кавычках.
Число используемых буквенных символов также определяет формат:
- Для текстового представления 1-3 символа указывают на сокращенную форму записи, тогда как 4+ символа – на полную форму.
- Для числовых представлений число символов указывает на минимальное требуемое число цифр. Более короткое число дополняется лидирующими нулями.
Источник
Simpledateformat android studio примеры
SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting. However, you are encouraged to create a date-time formatter with either getTimeInstance , getDateInstance , or getDateTimeInstance in DateFormat . Each of these class methods can return a date/time formatter initialized with a default format pattern. You may modify the format pattern using the applyPattern methods as desired. For more information on using these methods, see DateFormat .
Date and Time Patterns
Date and time formats are specified by date and time pattern strings. Within date and time pattern strings, unquoted letters from ‘A’ to ‘Z’ and from ‘a’ to ‘z’ are interpreted as pattern letters representing the components of a date or time string. Text can be quoted using single quotes ( ‘ ) to avoid interpretation. «»» represents a single quote. All other characters are not interpreted; they’re simply copied into the output string during formatting or matched against the input string during parsing.
The following pattern letters are defined (all other characters from ‘A’ to ‘Z’ and from ‘a’ to ‘z’ are reserved):
Letter Date or Time Component Presentation Examples G Era designator Text AD y Year Year 1996 ; 96 Y Week year Year 2009 ; 09 M Month in year Month July ; Jul ; 07 w Week in year Number 27 W Week in month Number 2 D Day in year Number 189 d Day in month Number 10 F Day of week in month Number 2 E Day name in week Text Tuesday ; Tue u Day number of week (1 = Monday, . 7 = Sunday) Number 1 a Am/pm marker Text PM H Hour in day (0-23) Number 0 k Hour in day (1-24) Number 24 K Hour in am/pm (0-11) Number 0 h Hour in am/pm (1-12) Number 12 m Minute in hour Number 30 s Second in minute Number 55 S Millisecond Number 978 z Time zone General time zone Pacific Standard Time ; PST ; GMT-08:00 Z Time zone RFC 822 time zone -0800 X Time zone ISO 8601 time zone -08 ; -0800 ; -08:00
Pattern letters are usually repeated, as their number determines the exact presentation:
- Text: For formatting, if the number of pattern letters is 4 or more, the full form is used; otherwise a short or abbreviated form is used if available. For parsing, both forms are accepted, independent of the number of pattern letters.
Number: For formatting, the number of pattern letters is the minimum number of digits, and shorter numbers are zero-padded to this amount. For parsing, the number of pattern letters is ignored unless it’s needed to separate two adjacent fields.
- For formatting, if the number of pattern letters is 2, the year is truncated to 2 digits; otherwise it is interpreted as a number.
- For parsing, if the number of pattern letters is more than 2, the year is interpreted literally, regardless of the number of digits. So using the pattern «MM/dd/yyyy», «01/11/12» parses to Jan 11, 12 A.D.
- For parsing with the abbreviated year pattern («y» or «yy»), SimpleDateFormat must interpret the abbreviated year relative to some century. It does this by adjusting dates to be within 80 years before and 20 years after the time the SimpleDateFormat instance is created. For example, using a pattern of «MM/dd/yy» and a SimpleDateFormat instance created on Jan 1, 1997, the string «01/11/12» would be interpreted as Jan 11, 2012 while the string «05/04/64» would be interpreted as May 4, 1964. During parsing, only strings consisting of exactly two digits, as defined by Character.isDigit(char) , will be parsed into the default century. Any other numeric string, such as a one digit string, a three or more digit string, or a two digit string that isn’t all digits (for example, «-1»), is interpreted literally. So «01/02/3» or «01/02/003» are parsed, using the same pattern, as Jan 2, 3 AD. Likewise, «01/02/-3» is parsed as Jan 2, 4 BC.
Otherwise, calendar system specific forms are applied. For both formatting and parsing, if the number of pattern letters is 4 or more, a calendar specific long form is used. Otherwise, a calendar specific short or abbreviated form is used.
If week year ‘Y’ is specified and the calendar doesn’t support any week years, the calendar year ( ‘y’ ) is used instead. The support of week years can be tested with a call to getCalendar() . isWeekDateSupported() .
Month: If the number of pattern letters is 3 or more, the month is interpreted as text; otherwise, it is interpreted as a number.
General time zone: Time zones are interpreted as text if they have names. For time zones representing a GMT offset value, the following syntax is used: Hours must be between 0 and 23, and Minutes must be between 00 and 59. The format is locale independent and digits must be taken from the Basic Latin block of the Unicode standard.
For parsing, RFC 822 time zones are also accepted.
RFC 822 time zone: For formatting, the RFC 822 4-digit time zone format is used: TwoDigitHours must be between 00 and 23. Other definitions are as for general time zones.
For parsing, general time zones are also accepted.
ISO 8601 Time zone: The number of pattern letters designates the format for both formatting and parsing as follows: Other definitions are as for general time zones or RFC 822 time zones.
For formatting, if the offset value from GMT is 0, «Z» is produced. If the number of pattern letters is 1, any fraction of an hour is ignored. For example, if the pattern is «X» and the time zone is «GMT+05:30» , «+05» is produced.
For parsing, «Z» is parsed as the UTC time zone designator. General time zones are not accepted.
If the number of pattern letters is 4 or more, IllegalArgumentException is thrown when constructing a SimpleDateFormat or applying a pattern.
SimpleDateFormat also supports localized date and time pattern strings. In these strings, the pattern letters described above may be replaced with other, locale dependent, pattern letters. SimpleDateFormat does not deal with the localization of text other than the pattern letters; that’s up to the client of the class.
Examples
Date and Time Pattern Result «yyyy.MM.dd G ‘at’ HH:mm:ss z» 2001.07.04 AD at 12:08:56 PDT «EEE, MMM d, »yy» Wed, Jul 4, ’01 «h:mm a» 12:08 PM «hh ‘o»clock’ a, zzzz» 12 o’clock PM, Pacific Daylight Time «K:mm a, z» 0:08 PM, PDT «yyyyy.MMMMM.dd GGG hh:mm aaa» 02001.July.04 AD 12:08 PM «EEE, d MMM yyyy HH:mm:ss Z» Wed, 4 Jul 2001 12:08:56 -0700 «yyMMddHHmmssZ» 010704120856-0700 «yyyy-MM-dd’T’HH:mm:ss.SSSZ» 2001-07-04T12:08:56.235-0700 «yyyy-MM-dd’T’HH:mm:ss.SSSXXX» 2001-07-04T12:08:56.235-07:00 «YYYY-‘W’ww-u» 2001-W27-3
Synchronization
Date formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally.
Источник
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»
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.
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».
Источник