Calculate date and time in java

Java 8 Date Time API

Java supports creating and modifying the date and time using primarily two packages java.time and java.util . The package java.time was part of Java 8 release (JSR-310) that introduced the new immutable classes solving the shortcomings of the legacy java.util.Date and java.util.Calendar classes.

1. Legacy Date Time API (Prior to Java 8)

The primary legacy classes to manipulate date and time were :

  • java.util.Date : represents a specific instant in time, with millisecond precision.
  • java.util.Calendar : an abstract class that provides methods for converting between instances and manipulating the calendar fields in difefrent ways.
  • java.text.SimpleDateFormat : a concrete class for formatting and parsing dates in a locale-sensitive manner and any predefined as well as any user-defined pattern.
  • java.util.TimeZone : represents a time zone offset, and also figures out daylight savings.
  • System.currentTimeMillis() : represents the current date and time as milliseconds since January 1st 1970.

Though these APIs served the simple use cases very much, still Java community continuously complained about the problems in effectively using these classes. For this reason, many other 3rd party libraries (e.g. Joda-Time or classes in Apache Commons) were more popular.

A few of the challenges were:

  • A Date class shall represent a date, but it represents an instance which has hour, minutes and seconds as well.
  • But Date doesn’t have any associated time zone. It picks up the default timezone automatically. You cannot represent a date some other timezone.
  • Classes are mutable. So that leaves additional burden on developers to clone the date before passing a function, which can mutate it.
  • Date formatting classes are also not thread-safe. A formatter instance cannot be used without additional synchronization, else code may break.
  • For some reason, there is another class java.sql.Date which has timzone information.
  • Creating a date with some other timezone is very tricky and often result in incorrect result.
  • Its classes use a zero-index for months, which is a cause of many bugs in applications over the years.

2. New Date Time API (Java 8 Onwards)

The new date api tries to fix the above problems with legacy classes. It contains mainly the following classes:

  • java.time.LocalDate : represents a year-month-day in the ISO calendar and is useful for representing a date without a time. It can be used to represent a date only information such as a birth date or wedding date.
  • java.time.LocalTime : deals in time only. It is useful for representing human-based time of day, such as movie times, or the opening and closing times of the local library.
  • java.time.LocalDateTime : handles both date and time, without a time zone. It is a combination of LocalDate with LocalTime.
  • java.time.ZonedDateTime : combines the LocalDateTime class with the zone information given in ZoneId class. It represent a complete date time stamp along with timezone information.
  • java.time.OffsetTime : handles time with a corresponding time zone offset from Greenwich/UTC, without a time zone ID.
  • java.time.OffsetDateTime : handles a date and time with a corresponding time zone offset from Greenwich/UTC, without a time zone ID.
  • java.time.Clock : provides access to the current instant, date and time in any given time-zone. Although the use of the Clock class is optional, this feature allows us to test your code for other time zones, or by using a fixed clock, where time does not change.
  • java.time.Instant : represents the start of a nanosecond on the timeline (since EPOCH) and useful for generating a timestamp to represent machine time. An instant that occurs before the epoch has a negative value, and an instant that occurs after the epoch has a positive value.
  • java.time.Duration : Differnce between two instants and 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.
  • java.time.Period : To define the difference between dates in date-based values (years, months, days).
  • java.time.ZoneId : specifies a time zone identifier and provides rules for converting between an Instant and a LocalDateTime.
  • java.time.ZoneOffset : specifies a time zone offset from Greenwich/UTC time.
  • java.time.format.DateTimeFormatter : provides numerous predefined formatters, or we can define our own. It provides parse() or format() method to parsing and formatting the date time values.
  • TemporalAdjusters : provide many useful inbuilt adjusters for handling recurring events.
  • TemporalQuery : be used as the assignment target for a lambda expression or method reference.
  • DayOfWeek : an enum representing the seven days of the week – Monday, Tuesday, Wednesday, Thursday, Friday, Saturday and Sunday.
Читайте также:  Php new data type

3. Performing Common Tasks

These examples use new classes introduced in Java 8 date time API.

3.1. Get Current Date and Time

All date-time classes have a factory method now() which is the preferred way to get the current date and time in Java 8.

LocalTime currentTime = LocalTime.now(); //13:33:43.557 LocalDate currentDate = LocalDate.now(); //2020-05-03 LocalDateTime currentDateTime = LocalDateTime.now(); //2020-05-03T13:33:43.557

Date parsing is done with the help of DateTimeFormatter class and parse() methods in date-time classes.

String dateString = "2020-04-08 12:30"; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); LocalDateTime parsedDateTime = LocalDateTime.parse(dateString, formatter); System.out.println(parsedDateTime); //2020-04-08T12:30

Date formatting is done with the help of DateTimeFormatter class and format() methods in date-time classes.

//Format a date LocalDateTime myDateObj = LocalDateTime.now(); DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm"); String formattedDate = myDateObj.format(myFormatObj); System.out.println(formattedDate); // 03-05-2020 13:46

To get the elapsed execution time in different time units, use methods such as toDays(), toHours(), toMillis(), toMinutes(), toNanos() and getSeconds() from the java.time.Instant and java.time.Duration classes.

Instant start = Instant.now(); //Measure execution time for this method methodToMeasureExecutionTime(); Instant finish = Instant.now(); long timeElapsed = Duration.between(start, finish).toMillis(); //in millis

3.5. Calculate Days between Two Dates

To calculate number of days between two dates in Java 8 using ChronoUnit.DAYS.between() and LocalDate.until() methods.

LocalDate date1 = LocalDate.now(); LocalDate date2 = date1.plusDays(99); long diffInDays = ChronoUnit.DAYS.between(date1, date2);

The purpose of this tutorial was to introduce you to the legacy Date/Time classes and the challenges faced by the programmers while working with these APIs. We also saw how the new APIs solve the existing challenges using the specific classes for representing the date and time information.

Also, we had a quick look at how to work with the new APIs.

Читайте также:  Java runtime environment or java development kit must be available in order to run eclipse

Источник

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 в строку и возвращает результат.

Текущая дата и время в 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(), который определяется сопоставимым интерфейсом и реализуется по дате.
Читайте также:  Php function include global

Форматирование даты с помощью 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); >> 

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

Источник

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