Date and time¶
One of the new features introduced in Java 8 is the new date and time API, also known as JSR-310, which is easy to understand, logical and largely similar to the Joda library (available even before Java 8). The main classes for date/time handling starting from local time will be discussed below.
Local time support (without TimeZone)¶
The main classes supporting local date and time (without time zones) are:
- java.time.LocalTime
- java.time.LocalDate
- java.time.LocalDateTime
- java.time.Instant
LocalTime¶
The class LocalTime
represents time, without linking it to a specific time zone or even a date. This is the time without the time zone in the calendar system ISO-8601
. It has some very useful methods:
- now() - a static method that returns the current time. The default format is
HH:mm:ss.mmm
(hours:minutes:seconds.milliseconds). Example:
LocalTime localTime = LocalTime.now();
System.out.println("Current time: " + localTime); // Current time: 22:34:27.106
- withHour(), withMinute(), withSecond(), withNano()-set the time, minutes, seconds and nanoseconds in the current
LocalTime
object, e.g:
LocalTime localTime = LocalTime.now()
.withSecond(0) // set the seconds to 0
.withNano(0); // set nanoseconds to 0
System.out.println("Current time: " + localTime); // Current time: 22:41
- plusNanos(x), plusSeconds(x), plusMinutes(x), plusHours(x), minusNanos(x), minusSeconds(x), minusMinutes(x), minusHours(x) - adding (subtraction) nanoseconds, seconds, minutes, hours to (from) the set time, e.g:
``java LocalTime now = LocalTime.now(); System.out.println("Current time: " + now); // Current time: 22:49:01.241 now = now.plusMinutes(10).plusHours(1); System.out.println("Current time after addition: " + now); // Current time after addition: 23:59:01.241
* **getHour()** - returns the time that the object represents
* **getMinute()** - returns the minute of time that the object represents
* **getSecond()** - returns the second time that the object represents
The example below shows how to format the hour, minutes and seconds from the current time in any way you want:
```java
LocalTime now = LocalTime.now();
String formattedTime = now.getHour() + ":" + now.getMinute() + ":" + now.getSecond();
System.out.println(formattedTime); // 22:55:26
LocalDate¶
The essence of the existence of the LocalDate
class is to represent the date (year, month, day). This object does not take into account and does not store the time (e.g. current time) or time zone. The date is stored in the format ISO-8601
by default. The main methods operating on local date objects are presented below:
- now() - a static method that returns the current date. The default format is
YYYY-mm-dd
, for example:
LocalDate now = LocalDate.now();
System.out.println(now); // 2020-03-27
- of(year, month, dayOfMonth) - creates an object representing a date (year, month, day). The month can be represented by the enum
java.time.Month
or the month index, e.g:
LocalDate localDate = LocalDate.of(2020, Month.MARCH, 28);
System.out.println(localDate); // 2020-03-28
- getYear() - returns the
int
representing the year - getMonth() - returns a month using the
java.time.Month
object. - getDayOfYear() - returns the
int
informing which day of the year - getDayOfMonth() - returns the
int
representing the day of the month - getDayOfWeek() - returns the day of the week using the enum
java.time.DayOfWeek
LocalDateTime¶
The essence of the existence of the class LocalDateTime
is the representation of date (year, month, day) and time (hour, minute, second, millisecond). This is a format without the time zone in the ISO-8601
calendar system. Here are some of the methods from this class that are most commonly used:
- now() - a static method that returns the current date and time. The default format is
YYYY-MM-ddThh:mm:ss.mmm
, e.g.
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(localDateTime); // 2020-03-28T20:25:16.124
- of(year, month, dayOfMonth, hour, minutes, seconds, milliseconds) - a static method that returns a local date and time according to the set parameters (year, month, day of the month, hour, minutes, seconds, milliseconds). There are also overloaded equivalents of this method with a variable number of parameters. Example below:
LocalDateTime localDateTime = LocalDateTime.of(2020, Month.MARCH, 28, 20, 0, 10, 0);
System.out.println(localDateTime); // 2020-03-28T20:00:10
In the value printed let's note that the sign T
is a conventional separator separating the date value from the time.
Instant¶
This class stands out from the others in that it represents a specific and clearly defined point in time (with an accuracy of one second). The second important feature is that it is not related to the concept of days or years, but only to the universal time, the so-called "time of the year". UTC. In short, it stores internally the number of seconds (to the nearest nanosecond) from a certain fixed point in time (1 January 1970 - the so-called Epoch time). It is best suited to represent time in a way that will be processed by the system and not displayed to end users. A class instance of the Instant
can be used to create instances of classes such as LocalTime
, LocalDate
or LocalDateTime
, e.g.
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
System.out.println(localDateTime); // 2020-04-19T18:33:29.116691800
LocalTime localTime = LocalTime.ofInstant(instant, ZoneId.of("CET"));
System.out.println(localTime); // 18:33:29.116691800
LocalDate localDate = LocalDate.ofInstant(instant, ZoneId.ofOffset("UTC", ZoneOffset.ofHours(2));
System.out.println(localDate); // 2020-04-19
The classes that represent the intervals¶
JSR-310
(JSR -Java Specification Request) introduces the concept of interval as the time that elapsed between moments A and B. There are two classes for this:
- java.time.Duration
- java.time.Period
They differ only in units (they allow to represent respectively: time units (Duration) and e.g. months or years (Period)). Examples follow:
System.out.println(Duration.ofHours(10).toMinutes()); // 10 hours expressed in minutes: 600
// In the example below, the time difference in minutes between the current time and the time 2 days later was calculated
System.out.println(Duration.between(LocalDateTime.now(), LocalDateTime.now().plusDays(2)).toMinutes()); // 2880
// The number of months between the two dates is calculated below.
System.out.println(Period.between(LocalDate.now(), LocalDate.now().plusDays(100)).getMonths()); // 3
The distinction between Duration
and Period
is based on a simple fact - all lengths expressed by Duration
are represented in basic units of time (i.e., e.g., in seconds), while those expressed by Period
(month, year, age, millennium) may have different real lengths (by different number of days in months, leap years, etc.).
Date display format¶
For formatting type objects: The LocalDate LocalTime LocalDateTime
is used by the format(formatter)
method. An example for local time is given below:
``java LocalTime localTime= LocalTime.now(); String formattedLocalTime = localTime.format(DateTimeFormatter.ISO_LOCAL_TIME); System.out.println(formattedLocalTime); // 21:11:00.024
Here is a list of predefined formats:
![date and time formatters](date_and time/datetime_formatters.png)
Apart from ready-made formats, we can also prepare our own implementations. For this purpose, we must use special symbols that have a specific meaning and representation, such as
``java
String date = LocalDate.now().format(DateTimeFormatter.ofPattern("MM:YYYY:dd"));
System.out.println(date); // 04:2020:19
A list and description of all available symbols for formatting the LocalDate LocalTime LocalDateTime
objects can be found here.