New date time API in JDK8

java.time: base package containing value objects

java.time.chrono: provides access to different calendar systems

java.time.format: format and parse time and date

Java. Time. Temporary: including the underlying framework and extension features contains classes that support time zones

Note: most developers use the basic package and format package, and may also use the temporary package. Therefore, although there are 68 new public types, most developers use about a third of them.


     LocalDate, LocalTime, and LocalDateTime are important classes. Their instances are immutable objects that represent the date, time, date, and time using the ISO-8601 calendar system. It 2 provides a simple local date or time, does not contain the current time information, nor does it contain information related to the time zone.

LocalDate: represents the date in IOS format (yyyy MM DD). It can store birthday, anniversary and other dates.

Local time: represents a time, not a date.

LocalDateTime: used to represent date and time. It is one of the most commonly used classes.

Note: ISO-8601 calendar system is the representation of the date and time of modern citizens formulated by the international organization for standardization, that is, the Gregorian calendar

now()/* now(Zoneld zone)Static method to create an object based on the current time / an object with a specified time zone
of()Static method to create an object based on a specified date / time
getDayOfMonth() / getDayOfYear()Days of acquisition month (1-31) / days of acquisition year (1-366)
getDayOfWeek()Gets the day of the week (returns a DayOfWeek enumeration value)
getMonth()Get the Month and return a Month enumeration value
getMonthValue() / getYear()Acquisition month (1-12) / acquisition year
getHour() / getMinute / getSecond()Obtain the hour, minute and second corresponding to the current object
withDayOfMonth() / withDayOfYear() / withMonth() / witjYear()Modify the month days, year days, month and year to the specified value and return a new object
plusDays(), plusWeeks(), plusMonths(), plusYears(), plusHours()Add days, weeks, months, years, hours to the current object
minusMonths(), minusWeeks(), minusDays(), minusYear(),minusHoursSubtract months, weeks, days, years, hours from the current object
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Date;

import static java.time.LocalDateTime.*;

jdk 8 Testing of date time API in
public class JDK8DateTimeTest {
    public void testDate(){
        Date date1=new Date(2020-1900,9-1,8);
        System.out.println(date1);//Tue Sep 08 00:00:00 GMT+08:00 2020

    LocalDate,LocalTime,LocalDateTime Use of
        1.LocalDateTime Compared with LocalDate and LocalTime
        2.Similar to Calendar
    public void test1(){
        //now(): get the current date, time, date + time
        LocalDateTime localDateTime=;


        //of(): set the specified year, month, day, hour, minute and second. No offset
        localDateTime localDateTime1=localDateTime.of(2021,9,8,10,33,22);

        //getXxx(): get related attributes

        //Reflect immutability
        localDate localDate1=localDate.withDayOfMonth(22);

        LocalDateTime localDateTime2=localDateTime.withHour(4);

        //Non variability plus month
        localDateTime localDateTime3=localDateTime.plusMonths(3);

        //Minus days
        localDateTime localDateTime4=localDateTime.minusDays(6);

Instantaneous: Instant

instant: an instantaneous point on the timeline. This may be used to record event timestamps in the application.

    When dealing with time and date, we usually think of year, month, day, hour, minute and second. However, this is only a model of time, which is human oriented. The second general model is machine oriented, or continuous. In this model, a point in the timeline is represented as a large number, which is conducive to computer processing. In UNIX, this number has been in seconds since 1970; Similarly, in Java, it began in 1970, but in milliseconds.

    The java.time package provides machine attempts through the value type instant, and does not provide time units in the human sense. Instant represents a point on the timeline without any contextual information, such as time zone. Conceptually, it simply represents the number of seconds since 0:0:0 (UTC) on January 1, 1970. Because the java.time package is based on Nanosecond calculation, the accuracy of instant can reach nanosecond level.

    (1ns=10^(-9)s) 1s = 1000 ms = 10 ^ 6 microseconds = 10 ^ 9 nanoseconds

now()Static method that returns the object of the Instant class of the default UTC time zone
ofEpochMilli(long epochMilli)Static method, which returns the object of the Instant class based on 1970-01-01 00:00:00 plus the specified number of milliseconds
atOffset(ZoneOffset offset)Create an OffsetDateTime in combination with the real-time offset
toEpochMilli()Returns the number of milliseconds from 1970-01-01 00:00:00 to the current time, which is the timestamp

    Timestamp refers to the total number of seconds from 00:00:00 GMT on January 1, 1970 (08:00:00 GMT on January 1, 1970) to the present.

    Instant Use of
    Similar to the java.util.Date class
    public void test2(){
        //now(): get the standard time corresponding to the original meridian

        //Add offset of time
        OffsetDateTime offsetDateTime=instant.atOffset(ZoneOffset.ofHours(8));

        //Toepochmili(): get the number of milliseconds since 0:0:0 (UTC) on January 1, 1970 -- > getTime() method of date class
        long milli=instant.toEpochMilli();

        //Ofepochmili(): obtain the Instant instance through the given number of milliseconds - > date (long millis);
        Instant instant1=Instant.ofEpochMilli(1550475314878L);

java.time.format.DateTimeFormatter class:

This class provides three formatting methods:

1) Predefined standard formats, such as ISO_LOCAK_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIMR

2) Localization related formats. For example: ofLocalized(FormatStyle.LONG)

3) Custom format. For example: ofpattern ("yyyy MM DD HH: mm: SS e")

ofPattern(String pattern)Static method that returns a DateTimeFormatter in the specified string format
format(TemporalAccessoor t)Format a date and time and return a string
parse(CharSequence text)Parses the character sequence in the specified format into a date and time
    DateTimeFormatter:Format or parse date and time
    Similar to SimpleDateFormat
    public void test3(){
        //Method 1: predefined standard format, such as ISO_LOCAK_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIMR
        DateTimeFormatter formatter=DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        //Format: date - > string
        String str1=formatter.format(localDateTime);

        //Parsing: String - > date
        TemporalAccessor parse=formatter.parse("2021-09-08T16:05:18.787");

        //Mode 2: localize related formats. For example: ofLocalized(FormatStyle.LONG)
        DateTimeFormatter formatter1=DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT);
        String str2=formatter1.format(localDateTime);

        DateTimeFormatter formatter2=DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL);
        String str3=formatter2.format(;

        //Key point: Method 3: custom format. For example: ofpattern ("yyyy MM DD HH: mm: SS e")
        DateTimeFormatter formatter3=DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
        String str4=formatter1.format(;
        System.out.println(str4);//2021-09-08 04:34:16
        TemporalAccessor accessor=formatter3.parse("2021-09-08 04:34:16");


Other API s:

Zoneld: this class contains all time zone information, including the ID of a time zone, such as Europe/Paris

ZonedDateTime: a date and time in the time zone of the ISO-8601 calendar system, such as 2021-09-03T10:15:30+01:00 Europe/Paris. (each time zone corresponds to an ID, and the region ID is in the format of "{region} / {City}", such as Asia/Shanghai, etc.)

Clock: a clock that uses a time zone to provide access to the current instant, date, and time.

Duration: used to calculate two "time" intervals

Date interval Perido: used to calculate two "date" intervals

TemporalAdjuster: time corrector. Sometimes we may want to obtain operations such as adjusting the date to "next working day".

TemporalAdjusters: This provides a large number of common implementations of TemporalAdjusters through static methods (firstDayOfXxx()/lastDayOfXxx()/nextXxx()).

Reference: conversion from traditional date processing

classTo legacy classFrom legacy class
java.time.Instant and java.util.DataDate.from(instant)date.toInstant()
java.time.Instant and java.sql.TimestampTimestamp.from(instant)timestamp.toInstant()
java.time.ZonedDateTime and java.util.GregorianCalendarGregorianCalendar.from(zonedDate Time)cal.toZonedDateTime()
java.time.LocalDate and java.sql.TimeDate.valueOf(localDate)date.toLocalDate()
java.time.LocalTime and java.sql.TimeDate.valueOf(localDate)date.toLocalDate()
java.time.LocalDateTime and java.sql.TimestampTimestamp.valueOf(localDateTime)timestamp.toLocalDateTime()
java.time.Zoneld and java.util.TimeZoneTimezone.getTimeZone(id)timeZone.toZoneld()
java.time.format.DateTimeFormatter and java.text.DateFormatformatter.toFormat()nothing

Tags: Java

Posted on Tue, 23 Nov 2021 19:02:18 -0500 by psgarcha