
1. overview
Java 8 introduces new APIs for Date and Time to solve the problem of oldjava.util.Date
andjava.util.Calendar
shortcomings. As part of this article, let's start by looking at some of the issues with existing Date and Calendar APIs and explore how the new Java 8 Date and Time APIs solve these issues. We will also work on core classes in the Java 8 Time Class Library, such asLocalDate
, LocalTime
, LocalDateTime
, ZonedDateTime
, Period
, Duration
and their apis.
2. Problems with the old time API (before java8)
- thread-safe–
Date
andCalendar
Classes are not thread-safe, making it difficult for developers to debug concurrency issues in these APIs and requiring additional code to be written to handle thread safety. The new Date and Time APIs introduced in Java 8 are immutable and thread-safe, allowing these pain points to be addressed. - API design and easy-to-understand Old time APIs are very difficult to understand, very complex to operate, very round-about, and do not provide some commonly used parsing and conversion methods. The new time API is ISO-centric and follows a consistent domain model of date, time, duration and periods. Provides some very practical methods to support the most common operations. We no longer need to encapsulate some time operation classes ourselves and describe them semantically.
- ZonedDate and Time In the old time api, developers had to write additional logic to handle the time zone logic of the old API, while with the new API, they could use the Local and ZonedDate / Time APIs to handle the time zone. Don't worry too much about time zone conversion issues.
3. Using LocalDate, LocalTime and LocalDateTime
The most commonly used classes areLocalDate
,LocalTime
andLocalDateTime
。As their name suggests, they represent the local date/time combined with the context.
These classes are mainly used when you do not need to explicitly specify the time zone in the context. As part of this section, we will introduce the most commonly used APIs.
3.1 Using LocalDate
LocalDate
Represents in ISO format (YYYY-MM-DD
) without specific time. Often used to indicate birthdays or the date we care about most about when we are paid. Get the date under the current system clock, as follows:
LocalDate localDate = LocalDate.now();
LocalDate representing specific days, months and years can be obtained using the "of" method or using the "parse" method. For example, the following code fragment represents LocalDate on February 20, 2015:
LocalDate.of(2015, 02, 20); LocalDate.parse("2015-02-20");
Is it very intuitive and convenient! LocalDate provides various practical methods to obtain various date information. Let's take a quick look at these API methods. The following code snippet gets the current local date and adds a day:
LocalDate tomorrow = LocalDate.now().plusDays(1)
;
This example takes the current date and subtracts one month. Notice how it accepts enumerations as units of time:
LocalDate previousMonthSameDay = LocalDate.now().minus(1, ChronoUnit.MONTHS);
In the following two code examples, we analyze the date "2016-06-12" and get the day of the week and the day of the month respectively. Notice the return values, the first one is the object that represents DayOfWeek, and the second one is the int that represents the ordinal value of the month:
DayOfWeek sunday = LocalDate.parse("2019-06-12").getDayOfWeek();
int twelve = LocalDate.parse("2016-09-12").getDayOfMonth();
We can also test whether a date occurs in a leap year. If we use the old method, we may not be going to heaven:
boolean leapYear = LocalDate.now().isLeapYear();
Determine the order of dates:
boolean notBefore = LocalDate.parse("2019-06-12").isBefore(LocalDate.parse("2019-06-11"));
boolean isAfter = LocalDate.parse("2019-06-12") .isAfter(LocalDate.parse("2019-06-11"));
Date boundaries can be obtained from a given date. In the following two examples, we get LocalDateTime, which represents the start of the day on the given date (2016-06- 12T00: 00) and the LocalDate at the beginning of the month (2019-06-01):
LocalDateTime beginningOfDay = LocalDate.parse("2019-06-12").atStartOfDay();
LocalDate firstDayOfMonth = LocalDate.parse("2019-09-12").with(TemporalAdjusters.firstDayOfMonth());
Now let's take a look at how we use local timeLocalTime
。
3.2 Using LocalTime
Represents time without date in local time. withLocalDate
Similarly, you can create LocalTime instances from the system clock or using the "parse" and "of" methods. A quick look at some of the commonly used APIs below. You can create an instance of the current LocalTime from the system clock, as follows:
LocalTime now = LocalTime.now();
In the following code example, we create aLocalTime
:
LocalTime sixThirty = LocalTime.parse("06:30");
Method "of" can be used to createLocalTime
。For example, the following code uses the "of" method to create aLocalTime
:
LocalTime sixThirty = LocalTime.of(6, 30);
The following example is created by parsing a stringLocalTime
, and add it for an hour using the "plus" API. The result will be a representative of 07:30 AMLocalTime
:
LocalTime sevenThirty = LocalTime.parse("06:30").plus(1, ChronoUnit.HOURS);
Various getter methods can be used to get specific units of time, such as hours, minutes, and seconds, and get hours as follows:
int six = LocalTime.parse("06:30").getHour();
withLocalDate
Also check whether a specific time is before or after another specific time. The following code example compares the results as followstrue
the twoLocalTime
:
boolean isbefore = LocalTime.parse("06:30").isBefore(LocalTime.parse("07:30"));
The maximum, minimum and noon times of the day can be obtained from constants in the LocalTime class. This is useful when performing database queries to find records within a given time range. For example, the following code represents23:59:59.99
:
LocalTime maxTime = LocalTime.MAX;
Now let's take a deeper look atLocalDateTime
。
3.3 Using LocalDateTime
The LocalDateTime is used to represent a combination of date and time. This is the most commonly used class when we need to combine date and time. This class provides various APIs, and we will introduce some of the most commonly used APIs. similar toLocalDate
andLocalTime
Obtained from system clockLocalDateTime
Examples of:
LocalDateTime.now();
The following code example explains how to create an instance using the factory "of" and "parse" methods. The result will be representativeFebruary 20, 2019 06:30 AM
theLocalDateTime
Example:
LocalDateTime.of(2019, Month.FEBRUARY, 20, 06, 30);
LocalDateTime.parse("2019-02-20T06:30:00");
There are some practical APIs that support time calculations for specific units of time, such as days, months, years, and minutes. The following code example demonstrates the use of the Add and Subtract methods. The behavior of these APIs is related toLocalDate
andLocalTime
The APIs in are exactly the same:
localDateTime.plusDays(1);
localDateTime.minusHours(2);
The Getter method can be used to extract specific units similar to date and time classes. in view of the aboveLocalDateTime
Example, the following code example will return the month of February:
localDateTime.getMonth();
4. Using the ZonedDateTime API
When we need to deal with time zone specific dates and times, Java 8 providesZonedDateTime
Class. ZoneID is an identifier used to represent different areas. There are about 40 different time zones, usingZoneID
Represents them as follows
Let's get the following code"Asia/Shanghai"
Time zone:
ZoneId zoneId = ZoneId.of("Aisa/Shanghai");
Get all time zones:
Set<String> allZoneIds = ZoneId.getAvailableZoneIds();
LocalDateTime
Convert to time in a specific time zone:
ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, zoneId);
ZonedDateTime provides parsing methods to obtain specific date and time in the time zone:
ZonedDateTime.parse("2019-06-03T10:15:30+01:00[Aisa/Shanghai]");
Another way to use time zones is to use theOffsetDateTime
。OffsetDateTime
Is an immutable representation of date and time with an offset. This class stores all date and time fields, accurate to nanoseconds, and offsets from UTC/Greenwich. may be usedZoneOffset
createOffsetDateTime
Examples. Here we create aLocalDateTime
representedFebruary 20, 2015 at 6:30 am
:
LocalDateTime localDateTime = LocalDateTime.of(2019, Month.FEBRUARY, 20, 06, 30);
And then we createdZoneOffset
and forLocalDateTime
Example settings to add two hours:
ZoneOffset offset = ZoneOffset.of("+02:00");
OffsetDateTime offSetByTwo = OffsetDateTime.of(localDateTime, offset);
We now assume that the local date and time is2019-02-20 06:30 +02:00
。Now let's continue discussing how to usePeriod
andDuration
Class modifies the date and time values.
5. Use Period and Duration
- Period : Used to calculate the interval between two dates (year, month, year).
- Duration : Used to calculate two time intervals (seconds, nanoseconds).
5.1 Use Period
Period
Class is widely used to modify the value of a given date or get the difference between two dates:
LocalDate initialDate = LocalDate.parse("2007-05-10");
LocalDate finalDate = initialDate.plus(Period.ofDays(5));
Period
Class has various getter methods, such asgetYears
,getMonths
andgetDays
Gets the value cycle object from. The following code example returns aint
A value of 5 is based on the reverse order operation in the above example:
int five = Period.between(finalDate, initialDate).getDays();
thePeriod
You can obtain data such as days or months or years between two dates in a specific unit, using theChronoUnit.between
:
int five = ChronoUnit.DAYS.between(finalDate , initialDate);
This code example returns five days. Let's keep lookingDuration
Class.
5.2 Use Duration
similarPeriod
,Duration
Class is used to process time. In the following code, we create a local time of 6:30 a.m., and then add a duration of 30 seconds to make the local time of 6:30 a.m.:
LocalTime initialTime = LocalTime.of(6, 30, 0);
LocalTime finalTime = initialTime.plus(Duration.ofSeconds(30));
The duration between two moments can be obtained as a duration or as a specific unit. In the first code fragment, we useDuration
classbetween()
way to findfinalTime
andinitialTime
and returns the difference in seconds:
int thirty = Duration.between(finalTime, initialTime).getSeconds();
In the second example, we useChronoUnit
classbetween()
Method to perform the same operation:
int thirty = ChronoUnit.SECONDS.between(finalTime, initialTime);
Now let's take a look at how to put the oldDate
andCalendar
converted to the newDate
andTime
。
6. Compatibility with dates and calendars
Java 8 addedtoInstant()
Method, which helps convert Date and Calendar instances from the old API to the new Date Time API, as shown in the following code fragment:
LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
LocalDateTime.ofInstant(calendar.toInstant(), ZoneId.systemDefault());
theLocalDateTime
It can be constructed from the following "ofEpochSecond" method. The result of the following code will be a representative2019-06-13T11:34:50
theLocalDateTime
:
LocalDateTime.ofEpochSecond(1465817690, 0, ZoneOffset.UTC);
Now let's continue with date and time formatting.
7. Date and time formatting
Java 8 provides APIs for easily formatting dates and times:
LocalDateTime localDateTime = LocalDateTime.of(2019, Month.JANUARY, 25, 6, 30);
The following code passes the ISO date format to format the local date. result will be2019-01-25
:
String localDateString = localDateTime.format(DateTimeFormatter.ISO_DATE);
theDateTimeFormatter
Various standard format options are available. You can also provide a custom pattern to format the method. Customize the above example as shown below, and it will returnLocalDate
for2019/01/25
:
localDateTime.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"))
;
We can pass the format style asSHORT
,LONG
orMEDIUM
As part of the formatting options. The following code example will be displayed in theJanuary 25, 2019 06:30:00
Give a representationLocalDateTime
Output of:
localDateTime.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).withLocale(Locale.UK);
Finally, let's take a look at the alternatives available to the Java 8 Core Date / Time API. Not all projects use Java 8.
8. alternative
8.1 Using the Threeten class library
For older projects from Java 7 or Java 6, you can use Threeten , and then you can use the same functionality as in Java 8 above. Once you migrate to Java 8, you only need to modify your package path code without changing it. You can use it immediately by referencing the following pom dependencies in your project:
<dependency>
<groupId>org.threeten</groupId>
<artifactId>threetenbp</artifactId>
<version>LATEST</version>
</dependency>
8.2 Joda-Time class library
Another alternative to the Java 8 date and time library is the veteran time processing class library Joda-Time. In fact, the Java 8 Date Time API absorbs a large number of Joda-Time libraries. This library provides almost all the features supported in the Java 8 Date Time project. You can use it immediately by referencing the following pom dependencies in your project:
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>LATEST</version>
</dependency>
Comments0