- Преобразование строки в дату в Java
- 1. Обзор
- Дальнейшее чтение:
- Преобразование java.util.Дата в строку
- Проверьте, является ли строка Допустимой датой в Java
- Преобразование между строкой и меткой времени
- 2. Преобразование строки в локальную дату или LocalDateTime
- 2.1. Использование API синтаксического анализа
- 2.2. Использование API Синтаксического анализа С помощью Пользовательского форматера
- 2.3. Общие шаблоны дат и времени
- 3. Преобразование строки в java.util.Date
- 3.1. Добавление информации о часовом поясе в java.util.Date
- 4. Внешние библиотеки
- 4.1. Библиотека Joda-Time
- 4.2. Apache Commons Lang – DateUtils
- 5. Заключение
- How to convert String to Date – Java
- 1. String = 7-Jun-2013
- 2. String = 07/06/2013
- 3. String = Fri, June 7 2013
- 4. String = Friday, Jun 7, 2013 12:10:56 PM
- 5. String = 2014-10-05T15:23:01Z
- References
- Comments
- Date from string java android
- Constructor Summary
- Method Summary
- Methods inherited from class java.lang.Object
- Constructor Detail
- Method Detail
- clone
- parse
Преобразование строки в дату в Java
Узнайте, как получить объект, представляющий дату, из строки в Java
Автор: Jonathan Cook
Дата записи
1. Обзор
В этом уроке мы рассмотрим несколько способов преобразования String объектов в Data objects . Мы начнем с нового Даты и времени API, java.time , который был представлен в Java 8 перед просмотром старого java.util.Тип данных Date также используется для представления дат.
В заключение мы рассмотрим некоторые внешние библиотеки для преобразования с использованием Joda-Time и класса Apache Commons Lang DateUtils .
Дальнейшее чтение:
Преобразование java.util.Дата в строку
Проверьте, является ли строка Допустимой датой в Java
Преобразование между строкой и меткой времени
2. Преобразование строки в локальную дату или LocalDateTime
LocalDate и LocalDateTime являются неизменяемыми объектами даты и времени, которые представляют дату, а также дату и время соответственно. По умолчанию даты Java находятся в формате ISO-8601, поэтому, если у нас есть какая-либо строка, представляющая дату и время в этом формате, то мы можем использовать parse() API этих классов напрямую .
Вот немного более подробно об этом новом API.
2.1. Использование API синтаксического анализа
T he Date-Time API предоставляет parse() методы для анализа Строки , содержащей информацию о дате и времени. Для преобразования строковых объектов в объекты LocalDate и LocalDateTime Строка должна представлять действительную дату или время в соответствии с ISO_LOCAL_DATE или ISO_LOCAL_DATE_TIME .
В противном случае во время выполнения будет выдано исключение DateTimeParseException .
В нашем первом примере давайте преобразуем String в java.time . LocalDate :
Аналогичный подход к вышесказанному может быть использован для преобразования String в java.time . LocalDateTime :
Важно отметить, что объекты LocalDate и LocalDateTime не зависят от часового пояса. Однако когда нам нужно иметь дело с конкретными датами и временем часового пояса, мы можем использовать метод ZonedDateTime parse напрямую, чтобы получить конкретную дату и время часового пояса:
Теперь давайте посмотрим, как мы преобразуем строки в пользовательский формат.
2.2. Использование API Синтаксического анализа С помощью Пользовательского форматера
Преобразование String с пользовательским форматом даты в объект Date является широко распространенной операцией в Java.
Для этой цели мы будем использовать класс DateTimeFormatter , который предоставляет множество предопределенных форматеров, и позволяет нам определить форматер.
Давайте начнем с примера использования одного из предопределенных форматов DateTimeFormatter :
В следующем примере давайте создадим форматер, который применяет формат “EEE, MMM d yyyy.” Этот формат определяет три символа для полного названия дня недели, одну цифру для обозначения дня месяца, три символа для обозначения месяца и четыре цифры для обозначения года.
Этот форматер распознает такие строки, как ” Пт, 3 января 2003 года” или “Ср, 23 марта 1994 года “:
2.3. Общие шаблоны дат и времени
Давайте рассмотрим некоторые общие шаблоны дат и времени:
- y – Год (1996; 96)
- M – Месяц в году (Июль; Июль; 07)
- d – День в месяце (1-31)
- E – Название дня в неделе (пятница, воскресенье)
- a– маркер AM/PM (AM, PM)
- Ч – Час в день (0-23)
- ч – Час в AM/PM (1-12)
- м – Минута в час (0-60)
- s – Секунда в минуту (0-60)
Для получения полного списка символов, которые мы можем использовать для указания шаблона для синтаксического анализа, нажмите здесь .
Если нам нужно преобразовать java.time dates в более старый java.util.Дата объект, прочитайте эту статью для получения более подробной информации.
3. Преобразование строки в java.util.Date
До Java 8 механизм даты и времени Java обеспечивался старыми API java.util.Дата , java.util.Календарь и java.util.Часовой пояс классы, с которыми нам иногда все еще нужно работать.
Давайте посмотрим, как преобразовать строку в java.util.Дата объект:
В приведенном выше примере нам сначала нужно построить SimpleDateFormat объект , передав шаблон, описывающий формат даты и времени.
Далее нам нужно вызвать метод parse() , передающий дату Строку . Если переданный аргумент String не имеет того же формата, что и шаблон, то будет выдано исключение ParseException .
3.1. Добавление информации о часовом поясе в java.util.Date
Важно отметить, что java.util.Дата не имеет понятия часового пояса и представляет только количество секунд , прошедших с момента времени эпохи Unix – 1970-01-01T00:00:00Z.
Однако, когда мы печатаем объект Date напрямую, он всегда будет печататься с системным часовым поясом Java по умолчанию.
В этом последнем примере мы рассмотрим, как отформатировать дату при добавлении информации о часовом поясе:
Мы также можем программно изменить часовой пояс JVM, но это не рекомендуется:
4. Внешние библиотеки
Теперь, когда у нас есть хорошее понимание того, как преобразовать String объекты в Date объекты, используя новые и старые API, предлагаемые core Java, давайте рассмотрим некоторые внешние библиотеки.
4.1. Библиотека Joda-Time
Альтернативой ядру Java Date и Time библиотеки является Joda-Time . Хотя авторы теперь рекомендуют пользователям перейти на java.time (JSR-310), если это невозможно, библиотека Joda-Time предоставляет отличную альтернативу для работы с датой и временем . Эта библиотека предоставляет практически все возможности, поддерживаемые в проекте Java 8 Date Time .
Артефакт можно найти на Maven Central :
Вот краткий пример работы со стандартным DateTime :
Давайте также рассмотрим пример явной установки часового пояса:
4.2. Apache Commons Lang – DateUtils
Класс DateUtils предоставляет множество полезных утилит, облегчающих работу с устаревшими объектами Calendar и Date |.
Артефакт commons-lang3 доступен в Maven Central :
Давайте преобразуем дату Строку в java.util.Дата использование Массива шаблонов дат:
5. Заключение
В этой статье мы проиллюстрировали несколько способов преобразования строк в различные типы объектов Data (со временем и без времени), как в обычной Java, так и с использованием внешних библиотек.
Полный исходный код статьи доступен на GitHub .
Источник
How to convert String to Date – Java
By mkyong | Last updated: March 10, 2017
Viewed: 1,690,897 (+721 pv/w)
In this tutorial, we will show you how to convert a String to java.util.Date . Many Java beginners are stuck in the Date conversion, hope this summary guide will helps you in some ways.
Refer to table below for some of the common date and time patterns used in java.text.SimpleDateFormat , refer to this JavaDoc
Letter | Description | Examples |
y | Year | 2013 |
M | Month in year | July, 07, 7 |
d | Day in month | 1-31 |
E | Day name in week | Friday, Sunday |
a | Am/pm marker | AM, PM |
H | Hour in day | 0-23 |
h | Hour in am/pm | 1-12 |
m | Minute in hour | 0-60 |
s | Second in minute | 0-60 |
1. String = 7-Jun-2013
If 3 ‘M’, then the month is interpreted as text (Mon-Dec), else number (01-12).
2. String = 07/06/2013
3. String = Fri, June 7 2013
4. String = Friday, Jun 7, 2013 12:10:56 PM
5. String = 2014-10-05T15:23:01Z
Z suffix means UTC, java.util.SimpleDateFormat doesn’t parse it correctly, you need to replace the suffix Z with ‘+0000’.
In Java 8, you can convert it into a java.time.Instant object, and display it with a specified time zone.
References
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.
Comments
Hi I have a requirement to convert DateofBirth, StartDate and TerminationDate fields in a file with about 100 lines. The current date format is 00.00.0000 and the requirement is 00/00/0000.
Thanks. This came in handy for me!
How to convert below string “2020-11-22T05:57:10+01:00” using Java8 ?
Hi
How to handle the format “2020–03–01 3:15 pm”?
Yoo solor quiero insertar una hora en mi base de datos y no entiendo nada!! el dato de mi base de datos es date, pero solo quiero pner hora por ejemplo 2:30 solo eso
In Method 4 4. String = Friday, Jun 7, 2013 12:10:56 PM
my requirement is if time is less than 12 (Friday, Jun 7, 2013 11:10:56 PM ) i am getting Unparseable date:
But in 12 hours format that is how we will write date.
Hello Sir,
I would like to ask, how to convert six june 1990 to 06/06/1990. Thanks
Do any one know what will be the formatter for this: 2018-06-19 14:59:29.0T-07:00
Thank you!
Hello Sir,
In example 5th the string i have passed is String = 14-10-05T15:23:01Z so in this case the output which i am getting is
Sun Oct 05 23:23:01 MYT 0014
time zone : Asia/Kuala_Lumpur
0014-10-05T23:23:01+0800
instead of parse exception which is causing data corruption. Please help how to handle this case ?
hello in my DB i Have declared month like a Long type ..so in my function I wan to use month like a Long value not String ..example : July i need it 07
How to proceed for that conversion ?
Hi Mkyong, Thanks. This came in handy for me!
Источник
Date from string java android
Prior to JDK 1.1, the class Date had two additional functions. It allowed the interpretation of dates as year, month, day, hour, minute, and second values. It also allowed the formatting and parsing of date strings. Unfortunately, the API for these functions was not amenable to internationalization. As of JDK 1.1, the Calendar class should be used to convert between dates and time fields and the DateFormat class should be used to format and parse date strings. The corresponding methods in Date are deprecated.
Although the Date class is intended to reflect coordinated universal time (UTC), it may not do so exactly, depending on the host environment of the Java Virtual Machine. Nearly all modern operating systems assume that 1 day = 24 × 60 × 60 = 86400 seconds in all cases. In UTC, however, about once every year or two there is an extra second, called a «leap second.» The leap second is always added as the last second of the day, and always on December 31 or June 30. For example, the last minute of the year 1995 was 61 seconds long, thanks to an added leap second. Most computer clocks are not accurate enough to be able to reflect the leap-second distinction.
Some computer standards are defined in terms of Greenwich mean time (GMT), which is equivalent to universal time (UT). GMT is the «civil» name for the standard; UT is the «scientific» name for the same standard. The distinction between UTC and UT is that UTC is based on an atomic clock and UT is based on astronomical observations, which for all practical purposes is an invisibly fine hair to split. Because the earth’s rotation is not uniform (it slows down and speeds up in complicated ways), UT does not always flow uniformly. Leap seconds are introduced as needed into UTC so as to keep UTC within 0.9 seconds of UT1, which is a version of UT with certain corrections applied. There are other time and date systems as well; for example, the time scale used by the satellite-based global positioning system (GPS) is synchronized to UTC but is not adjusted for leap seconds. An interesting source of further information is the U.S. Naval Observatory, particularly the Directorate of Time at:
and their definitions of «Systems of Time» at:
In all methods of class Date that accept or return year, month, date, hours, minutes, and seconds values, the following representations are used:
- A year y is represented by the integer y — 1900 .
- A month is represented by an integer from 0 to 11; 0 is January, 1 is February, and so forth; thus 11 is December.
- A date (day of month) is represented by an integer from 1 to 31 in the usual manner.
- An hour is represented by an integer from 0 to 23. Thus, the hour from midnight to 1 a.m. is hour 0, and the hour from noon to 1 p.m. is hour 12.
- A minute is represented by an integer from 0 to 59 in the usual manner.
- A second is represented by an integer from 0 to 61; the values 60 and 61 occur only for leap seconds and even then only in Java implementations that actually track leap seconds correctly. Because of the manner in which leap seconds are currently introduced, it is extremely unlikely that two leap seconds will occur in the same minute, but this specification follows the date and time conventions for ISO C.
In all cases, arguments given to methods for these purposes need not fall within the indicated ranges; for example, a date may be specified as January 32 and is interpreted as meaning February 1.
Constructor Summary
Constructor and Description |
---|
Date () |
Method Summary
Modifier and Type | Method and Description |
---|---|
boolean | after (Date when) |
Methods inherited from class java.lang.Object
Constructor Detail
Method Detail
clone
parse
It accepts many syntaxes; in particular, it recognizes the IETF standard date syntax: «Sat, 12 Aug 1995 13:30:00 GMT». It also understands the continental U.S. time-zone abbreviations, but for general use, a time-zone offset should be used: «Sat, 12 Aug 1995 13:30:00 GMT+0430» (4 hours, 30 minutes west of the Greenwich meridian). If no time zone is specified, the local time zone is assumed. GMT and UTC are considered equivalent.
The string s is processed from left to right, looking for data of interest. Any material in s that is within the ASCII parenthesis characters ( and ) is ignored. Parentheses may be nested. Otherwise, the only characters permitted within s are these ASCII characters:
A consecutive sequence of decimal digits is treated as a decimal number:
- If a number is preceded by + or - and a year has already been recognized, then the number is a time-zone offset. If the number is less than 24, it is an offset measured in hours. Otherwise, it is regarded as an offset in minutes, expressed in 24-hour time format without punctuation. A preceding - means a westward offset. Time zone offsets are always relative to UTC (Greenwich). Thus, for example, -5 occurring in the string would mean «five hours west of Greenwich» and +0430 would mean «four hours and thirty minutes east of Greenwich.» It is permitted for the string to specify GMT, UT, or UTC redundantly-for example, GMT-5 or utc+0430.
- The number is regarded as a year number if one of the following conditions is true:
- The number is equal to or greater than 70 and followed by a space, comma, slash, or end of string
- The number is less than 70, and both a month and a day of the month have already been recognized
If the recognized year number is less than 100, it is interpreted as an abbreviated year relative to a century of which dates are within 80 years before and 19 years after the time when the Date class is initialized. After adjusting the year number, 1900 is subtracted from it. For example, if the current year is 1999 then years in the range 19 to 99 are assumed to mean 1919 to 1999, while years from 0 to 18 are assumed to mean 2000 to 2018. Note that this is slightly different from the interpretation of years less than 100 that is used in SimpleDateFormat .
- If the number is followed by a colon, it is regarded as an hour, unless an hour has already been recognized, in which case it is regarded as a minute.
- If the number is followed by a slash, it is regarded as a month (it is decreased by 1 to produce a number in the range 0 to 11), unless a month has already been recognized, in which case it is regarded as a day of the month.
- If the number is followed by whitespace, a comma, a hyphen, or end of string, then if an hour has been recognized but not a minute, it is regarded as a minute; otherwise, if a minute has been recognized but not a second, it is regarded as a second; otherwise, it is regarded as a day of the month.
A consecutive sequence of letters is regarded as a word and treated as follows:
- A word that matches AM, ignoring case, is ignored (but the parse fails if an hour has not been recognized or is less than 1 or greater than 12).
- A word that matches PM, ignoring case, adds 12 to the hour (but the parse fails if an hour has not been recognized or is less than 1 or greater than 12).
- Any word that matches any prefix of SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, or SATURDAY, ignoring case, is ignored. For example, sat, Friday, TUE, and Thurs are ignored.
- Otherwise, any word that matches any prefix of JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, or DECEMBER, ignoring case, and considering them in the order given here, is recognized as specifying a month and is converted to a number (0 to 11). For example, aug, Sept, april, and NOV are recognized as months. So is Ma, which is recognized as MARCH, not MAY.
- Any word that matches GMT, UT, or UTC, ignoring case, is treated as referring to UTC.
- Any word that matches EST, CST, MST, or PST, ignoring case, is recognized as referring to the time zone in North America that is five, six, seven, or eight hours west of Greenwich, respectively. Any word that matches EDT, CDT, MDT, or PDT, ignoring case, is recognized as referring to the same time zone, respectively, during daylight saving time.
Once the entire string s has been scanned, it is converted to a time result in one of two ways. If a time zone or time-zone offset has been recognized, then the year, month, day of month, hour, minute, and second are interpreted in UTC and then the time-zone offset is applied. Otherwise, the year, month, day of month, hour, minute, and second are interpreted in the local time zone.
Источник