Java дата в период

17. Java – Дата и время

Java предоставляет класс Date, который доступен в пакете java.util, этот класс заключает в себе текущую дату и время.

Конструкторы

Класс Date поддерживает два конструктора, которые показаны ниже.

Конструктор и описание
1 Date()
Этот конструктор инициализирует объект с текущей датой и временем.
2 Date(long millisec)
Этот конструктор принимает аргумент равный числу миллисекунд, истекших с полуночи 1 января 1970 г.

Методы класса Date

Ниже представлены методы класса Date.

Методы с описанием
1 boolean after(Date date)
Возвращает значение true, если вызывающий объект date содержит дату, которая раньше заданной даты, в противном случае он возвращает значение false.
2 boolean before(Date date)
Возвращает значение true, если вызывающий объект date содержит дату, более раннюю, чем заданная дата, в противном случае он возвращает значение false.
3 Object clone()
Дублирование вызывающего объекта date.
4 int compareTo(Date date)
Сравнивает значение вызывающего объекта с этой датой. Возвращает 0, если значения равны. Возвращает отрицательное значение, если объект вызова является более ранним, чем дата. Возвращает положительное значение, если объект вызова позже даты.
5 int compareTo(Object obj)
Работает точно так же compareTo(Date), если объект вызова имеет класс Date. В противном случае вызывает ClassCastException.
6 boolean equals(Object date)
Возвращает значение true, если вызывающий объект date содержит то же время и дату, которая указана в date, в противном случае он возвращает значение false.
7 long getTime()
Возвращает количество миллисекунд, истекших с 1 января 1970 года.
8 int hashCode()
Возвращает хэш-код для вызывающего объекта.
9 void setTime(long time)
Задает дату и время, соответствующие моменту времени, что представляет собой общее затраченное время в миллисекундах от полуночи 1 января 1970 года.
10 String toString()
Преобразует вызывающий объект date в строку и возвращает результат.
Читайте также:  Centering image on page html

Текущая дата и время в Java

Получить текущую дату и время в Java достаточно не трудно. Вы можете использовать простой объект date вместе с методом toString(), чтобы вывести текущую дату и время следующим образом:

import java.util.Date; public class Test < public static void main(String args[]) < // Инициализация объекта date Date date = new Date(); // Вывод текущей даты и времени с использованием toString() System.out.println(date.toString()); >> 

Получим следующий результат:

Sun Nov 13 00:14:19 FET 2016 

Сравнение дат

Существуют три способа в Java сравнить даты:

  • Можно использовать функцию getTime(), чтобы получить количество миллисекунд, прошедших с момента полуночи 1 января 1970, для обоих объектов, а затем сравнить эти два значения.
  • Вы можете использовать методы before(), after() и equals(). Поскольку 12 число месяца раньше 18 числа, например, new Date(99, 2, 12).before(new Date (99, 2, 18)) возвращает значение true.
  • Можно использовать метод compareTo(), который определяется сопоставимым интерфейсом и реализуется по дате.

Форматирование даты с помощью SimpleDateFormat

SimpleDateFormat – это конкретный класс для парсинга и форматирования даты в Java. SimpleDateFormat позволяет начать с выбора любых пользовательских шаблонов для форматирования даты и времени. Например:

import java.util.*; import java.text.*; public class Test < public static void main(String args[]) < Date dateNow = new Date(); SimpleDateFormat formatForDateNow = new SimpleDateFormat("E yyyy.MM.dd 'и время' hh:mm:ss a zzz"); System.out.println("Текущая дата " + formatForDateNow.format(dateNow)); >> 

Получим следующий результат:

Текущая дата Вс 2016.11.13 и время 12:12:36 AM FET 

Формат-коды SimpleDateFormat

Для того, чтобы задать в Java формат даты и времени, используйте строковый шаблон (регулярные выражения) с датой и временем. В этой модели все буквы ASCII зарезервированы как шаблон письма, которые определяются следующим образом:

Символ Описание Пример
G Обозначение эры н.э.
y Год из четырех цифр 2016
M Номер месяца года 11
d Число месяца 13
h Формат часа в A.M./P.M.(1~12) 7
H Формат часа(0~23) 19
m Минуты 30
s Секунды 45
S Миллисекунды 511
E День недели Вс
D Номер дня в году 318
F Номер дня недели в месяце 2 (второе воскресение в этом месяце)
w Номер неделя в году 46
W Номер недели в месяце 2
a Маркер A.M./P.M. AM
k Формат часа(1~24) 24
K Формат часа в A.M./P.M.(0~11) 0
z Часовой пояс FET (Дальневосточноевропейское время)
Выделение для текста Текст
» Одинарная кавычка

Форматирование даты с помощью printf

Формат даты и времени можно сделать без труда с помощью метода printf. Вы используете формат двух букв, начиная с t и заканчивая одним из символов в таблице, приведенных ниже. Например:

import java.util.Date; public class Test < public static void main(String args[]) < // Инициализация объекта date Date date = new Date(); // Вывод текущей даты и времени с использованием toString() String str = String.format("Текущая дата и время: %tc", date); System.out.printf(str); >> 

Получим следующий результат:

Текущая дата и время: Вс ноя 13 00:55:59 FET 2016 

Было бы немного глупо, если Вы должны были бы поставить дату несколько раз для форматирования каждой части. По этой причине формат строки может указывать индекс аргумента для форматирования.

Индекс должен непосредственно следовать за % и завершаться $. Например:

import java.util.Date; public class Test < public static void main(String args[]) < // Инициализация объекта date Date date = new Date(); // Вывод текущей даты с использованием toString() System.out.printf("%1$s %2$td %2$tB %2$tY", "Дата:", date); >> 

Получим следующий результат:

Источник

Period and Duration

When you write code to specify an amount of time, use the class or method that best meets your needs: the Duration class, Period class, or the ChronoUnit.between method. A Duration measures an amount of time using time-based values (seconds, nanoseconds). A Period uses date-based values (years, months, days).

Note: A Duration of one day is exactly 24 hours long. A Period of one day, when added to a ZonedDateTime, may vary according to the time zone. For example, if it occurs on the first or last day of daylight saving time.

Duration

A Duration is most suitable in situations that measure machine-based time, such as code that uses an Instant object. A Duration object is measured in seconds or nanoseconds and does not use date-based constructs such as years, months, and days, though the class provides methods that convert to days, hours, and minutes. A Duration can have a negative value, if it is created with an end point that occurs before the start point.

The following code calculates, in nanoseconds, the duration between two instants:

Instant t1, t2; . long ns = Duration.between(t1, t2).toNanos();

The following code adds 10 seconds to an Instant:

Instant start; . Duration gap = Duration.ofSeconds(10); Instant later = start.plus(gap);

A Duration is not connected to the timeline, in that it does not track time zones or daylight saving time. Adding a Duration equivalent to 1 day to a ZonedDateTime results in exactly 24 hours being added, regardless of daylight saving time or other time differences that might result.

ChronoUnit

The ChronoUnit enum, discussed in the The Temporal Package, defines the units used to measure time. The ChronoUnit.between method is useful when you want to measure an amount of time in a single unit of time only, such as days or seconds. The between method works with all temporal-based objects, but it returns the amount in a single unit only. The following code calculates the gap, in milliseconds, between two time-stamps:

import java.time.Instant; import java.time.temporal.Temporal; import java.time.temporal.ChronoUnit; Instant previous, current, gap; . current = Instant.now(); if (previous != null) < gap = ChronoUnit.MILLIS.between(previous,current); >.

Period

To define an amount of time with date-based values (years, months, days), use the Period class. The Period class provides various get methods, such as getMonths, getDays, and getYears, so that you can extract the amount of time from the period.

The total period of time is represented by all three units together: months, days, and years. To present the amount of time measured in a single unit of time, such as days, you can use the ChronoUnit.between method.

The following code reports how old you are, assuming that you were born on January 1, 1960. The Period class is used to determine the time in years, months, and days. The same period, in total days, is determined by using the ChronoUnit.between method and is displayed in parentheses:

LocalDate today = LocalDate.now(); LocalDate birthday = LocalDate.of(1960, Month.JANUARY, 1); Period p = Period.between(birthday, today); long p2 = ChronoUnit.DAYS.between(birthday, today); System.out.println("You are " + p.getYears() + " years, " + p.getMonths() + " months, and " + p.getDays() + " days old. (" + p2 + " days total)");

The code produces output similar to the following:

You are 53 years, 4 months, and 29 days old. (19508 days total)

To calculate how long it is until your next birthday, you could use the following code from the Birthday example. The Period class is used to determine the value in months and days. The ChronoUnit.between method returns the value in total days and is displayed in parentheses.

LocalDate birthday = LocalDate.of(1960, Month.JANUARY, 1); LocalDate nextBDay = birthday.withYear(today.getYear()); //If your birthday has occurred this year already, add 1 to the year. if (nextBDay.isBefore(today) || nextBDay.isEqual(today)) < nextBDay = nextBDay.plusYears(1); >Period p = Period.between(today, nextBDay); long p2 = ChronoUnit.DAYS.between(today, nextBDay); System.out.println("There are " + p.getMonths() + " months, and " + p.getDays() + " days until your next birthday. (" + p2 + " total)");

The code produces output similar to the following:

There are 7 months, and 2 days until your next birthday. (216 total)

These calculations do not account for time zone differences. If you were, for example, born in Australia, but currently live in Bangalore, this slightly affects the calculation of your exact age. In this situation, use a Period in conjunction with the ZonedDateTime class. When you add a Period to a ZonedDateTime, the time differences are observed.

Источник

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