Извлечение года, месяца и дня из даты в Java
В этом коротком уроке мы рассмотрим, как извлечь год , месяц и день из данного Дата на Яве.
Мы рассмотрим, как извлечь эти значения с помощью устаревшего java.util.Класс Date , а также с помощью новой библиотеки даты и времени Java 8.
В Java 8 была введена совершенно новая библиотека даты и времени по ряду веских причин . Помимо других преимуществ, новая библиотека предоставляет лучший API для таких операций, как извлечение Года , Месяца , Дня и т.д. Из заданной Даты .
И, если вы ищете более подробную статью о новой библиотеке даты и времени, посмотрите здесь .
2. Использование Java 7
Для данного java.util.Дата для извлечения отдельных полей, таких как Год , Месяц , День и т.д. первый шаг, который нам нужно сделать, – это преобразовать его в Календарь экземпляр:
Date date = // the date instance Calendar calendar = Calendar.getInstance(); calendar.setTime(date);
Как только у нас есть экземпляр Calendar , мы можем напрямую вызвать его метод get и указать конкретное поле, которое мы хотим извлечь.
Мы можем использовать константы, присутствующие в Calendar , для извлечения определенных полей.
2.1. Получить Год
Чтобы извлечь год, мы можем вызвать get , передав Календарь.ГОД в качестве аргумента:
2.2. Получить месяц
Аналогично, чтобы извлечь месяц, мы можем вызвать get , передав Календарь.МЕСЯЦ в качестве аргумента:
Обратите внимание, что месяцы в Календаре индексируются с нулевой индексацией; для января этот метод вернет 0.
2.3. Получить День
Наконец, чтобы извлечь день, мы вызываем get , передавая Календарь.DAY_OF_MONTH в качестве аргумента:
calendar.get(Calendar.DAY_OF_MONTH);
3. Использование Java 8
Новый Новый пакет содержит ряд классов, которые могут быть использованы для представления Дата .
Каждый класс отличается дополнительной информацией, которую он хранит в дополнение к Дате .
Основные Локальные данные содержат только информацию о дате, в то время как LocalDateTime содержит данные, а также информацию о времени.
Аналогично, более продвинутые классы, такие как OffsetDateTime и ZonedDateTime , содержат дополнительную информацию о смещении от UTC и информацию о часовом поясе соответственно.
В любом случае, все эти классы поддерживают прямые методы для извлечения информации о годе, месяце и дате.
Давайте рассмотрим эти методы для извлечения информации из Локальных данных имени экземпляра локальной даты .
3.1. Получить Год
Чтобы извлечь Год, LocalDate просто предоставляет метод getYear :
3.2. Получить месяц
Аналогично, чтобы извлечь Месяц, мы используем getMonthValue API:
В отличие от Calendar , Месяцы в Local Date индексируются с 1; для января это вернет 1.
3.3. Получить День
Наконец, чтобы извлечь День, у нас есть getDayOfMonth метод:
4. Заключение
В этом кратком руководстве мы изучили, как извлечь целочисленные значения Год , Месяц и День из Дата в Java.
Мы показали, как извлечь эти значения, используя старые классы Date и Calendar , а также новую библиотеку даты и времени Java8.
Полный исходный код фрагментов, используемых в этом учебнике, доступен на Github .
Читайте ещё по теме:
Class Date
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 United States Naval Observatory (USNO):
and the material regarding «Systems of Time» at:
which has descriptions of various different time systems including UT, UT1, and UTC.
- 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
Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.
As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date) or GregorianCalendar(year + 1900, month, date) .
As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date, hrs, min) or GregorianCalendar(year + 1900, month, date, hrs, min) .
As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date, hrs, min, sec) or GregorianCalendar(year + 1900, month, date, hrs, min, sec) .
Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as «the epoch», namely January 1, 1970, 00:00:00 GMT.
Class Date
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 United States Naval Observatory (USNO):
and the material regarding «Systems of Time» at:
which has descriptions of various different time systems including UT, UT1, and UTC.
- 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
Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.
As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date) or GregorianCalendar(year + 1900, month, date) .
As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date, hrs, min) or GregorianCalendar(year + 1900, month, date, hrs, min) .
As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date, hrs, min, sec) or GregorianCalendar(year + 1900, month, date, hrs, min, sec) .
Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as «the epoch», namely January 1, 1970, 00:00:00 GMT.