Java8 new features of the time and date API
Java8 includes a new time and date API, which is placed under the java.time
package. This new time-date API is immutable and thread-safe (This class is immutable and thread-safe).
Local time: LocalDate, LocalTime, LocalDateTime
Instances of the classes localDate
, LocalTime
, and LocalDateTime
are immutable objects that represent the date, time, date, and time, respectively, using the ISO-8601 calendar system. They provide a simple date or time and do not contain current time information. Nor do they contain information related to the time zone.
localDate
,LocalTime
, andLocalDateTime
are used in exactly the same way.
Take localDateTime
as an example.
// Get the current date and time
LocalDateTime nowDateTime = LocalDateTime.now();
System.out.println(nowDateTime);
// Get the specified date and time
LocalDateTime assignDateTime = LocalDateTime.of(2017, 11, 22, 15, 23, 55);
System.out.println(assignDateTime);
// current time plus two years
LocalDateTime nowDateTimePlus2Years = nowDateTime.plusYears(2);
System.out.println(nowDateTimePlus2Years);
// Current time minus two years
LocalDateTime nowDateTimeMinus2Years = nowDateTime.minusYears(2);
System.out.println(nowDateTimeMinus2Years);
Output result.
2018-05-13T16:56:04.346 2017-11-22T15:23:55 2020-05-13T16:56:04.346 2016-05-13T16:56:04.346
Timestamp : Instant
Instant
: Timestamp, starting at 00:00:00 on January 1, 1970 and ending at a certain time in milliseconds.
// Get UTC time zone by default (UTC: Universal Time)
Instant instant1 = Instant.now();
System.out.println(instant1);
// Get the timestamp
long milli = instant1.toEpochMilli();
System.out.println(milli);
// with offset operation: offset by 8 hours: Beijing time
OffsetDateTime offsetDateTime = instant1.atOffset(ZoneOffset.ofHours(8));
System.out.println(offsetDateTime);
// add 60 seconds to the time stamp
Instant instant2 = Instant.ofEpochSecond(60);
System.out.println(instant2);
Output result.
2018-05-13T11:54:33.717Z 1526212473717 2018-05-13T19:54:33.717+08:00 1970-01-01T00:01:00Z
Calculation interval: Duration, Period
Duration
: Calculates the interval between two “times”.
Period
: Calculates the interval between two “dates”.
Calculates the interval between two “times”.
Instant instant1 = Instant.now();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Instant instant2 = Instant.now();
Duration duration = Duration.between(instant1, instant2);
System.out.println(duration.toMillis());
System.out.println("==================");
LocalTime time1 = LocalTime.now();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
LocalTime time2 = LocalTime.now();
System.out.println(Duration.between(time1, time2).toMillis());
1 4 12
Difference of 1 year, 4 months and 12 days.
Time corrector: TemporalAdjuster
TemporalAdjuster
: A time corrector, sometimes we may need to get, for example, to adjust the date to “next week as” and so on.
TemporalAdjusters
: This class provides a number of common TemporalAdjuster
implementations via static methods.
For example.
LocalDateTime dateTime = LocalDateTime.now();
// Specify the date
LocalDateTime dateTimeWithDayOfMonth = dateTime.withDayOfMonth(10);
// Specify the time using the time corrector: the next weekend
LocalDateTime dateTimeNextSunday = dateTime.with(TemporalAdjusters.next(DayOfWeek.SUNDAY));
System.out.println(dateTimeNextSunday);
// Custom time corrector: get the next weekday
LocalDateTime dateTime1 = dateTime.with((temporal) -> {
LocalDateTime time = (LocalDateTime)temporal;
DayOfWeek dayOfWeek = time.getDayOfWeek();
if (dayOfWeek.equals(DayOfWeek.FRIDAY)) {
return time.plusDays(3);
} else if (dayOfWeek.equals(DayOfWeek.SATURDAY)) {
return time.plusDays(2);
} else {
return time.plusDays(1);
}
});
System.out.println(dateTime1);
Time and date formatting: dateTimeFormatter
// Use the ISO standard date format
DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
LocalDateTime dateTime = LocalDateTime.now();
// Formatting method for LocalDateTime
String dateStr = dateTime.format(formatter);
System.out.println(dateStr);
// Using a custom date format
DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy year MM month dd day HH:mm:ss");
// DateTimeFormatter's formatting method
String dateStr2 = formatter1.format(dateTime);
System.out.println(dateStr2);
Handling of time zones: ZonedDate, ZonedTime, ZonedDateTime
Take
LocalDateTime
as an example.
Use the static LocalDateTime now(ZoneId zone)
method of LocalDateTime
to specify the time zone.
LocalDateTime dateTime = LocalDateTime.now(ZoneId.of("America/Los_Angeles"));
Result: 2018-05-13T06:24:47.349. shows the time in the Los Angeles time zone, USA.
To convert to ZonedDateTime
(time date object with time zone) using the ZonedDateTime atZone(ZoneId zone)
method of LocalDateTime
.
LocalDateTime dateTime2 = LocalDateTime.now();
ZonedDateTime zonedDateTime = dateTime2.atZone(ZoneId.of("America/Los_Angeles"));
System.out.println(zonedDateTime);
Result: 2018-05-13T06:24:47.446-07:00 [America/Los_Angeles]
ZonedDateTime
is the time date with time zone.