Java8 date time API, Java advanced multithreading interview

  • plusNanos(int offset): increases the specified nanosecond

Reduce related methods

  • minusYears(int offset): decrease the specified year

  • minusMonths(int offset): decrease the specified month

  • minusWeeks(int offset): decreases the specified week

  • minusDates(int offset): decrease the specified date

  • minusHours(int offset): decrease the specified time

  • minusMinuets(int offset): decreases the specified score

  • minusSeconds(int offset): decreases the specified second

  • minusNanos(int offset): decreases the specified nanosecond


public void test07() {

    //The method of the plusXXX system class that increases the amount of time returns a new date object

    LocalDateTime now =;


    //You can add time to the current date

    LocalDateTime newDate = now.plusYears(1);

    int year = newDate.getYear();



    //The method of subtracting the amount of time, the method of minusXXX series, returns a new date object

    LocalDate now1 =;


    LocalDate newDate2 = now1.minusDays(10);

    int dayOfMonth = newDate2.getDayOfMonth();



Output results







)Method for specifying time, minute and second of month, day and year

  • With (temporary adjuster): specify a special time

  • withYear(int year): Specifies the year

  • withDayOfYear(int dayOfYear): Specifies the day

  • withMonth(int month): Specifies the month

  • withDayOfMonth(int dayOfMonth): Specifies the day


public void test08() {

    //The method of specifying a date is the with() method

    LocalDate now2 =;


    LocalDate localDate = now2.withYear(2014);


    // TemporalAdjusters tool class provides some methods to get special dates

    LocalDate with = now2.with(TemporalAdjusters.firstDayOfMonth());


    LocalDate with1 = now2.with(TemporalAdjusters.firstDayOfNextMonth());


    //Get the day of the week of the month, such as temporaladjusters dayOfWeekInMonth(2, DayOfWeek.FRIDAY)

    // What date is the second Friday of this month

    LocalDate with2 = now2.with(TemporalAdjusters.dayOfWeekInMonth(2, DayOfWeek.FRIDAY));



Output results







)Method to format a date as a string

  • format(): format string

public void test03() {

    //Gets the hour, minute and second of the current date

    LocalDateTime now =;

    //Default format year month day T hour: minute: Second


    //Specify format

    DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyy year MM month dd day HH Time mm branch ss second");

    //Incoming format

    String dateStr = now.format(ofPattern);



Output results


2020 16:06:12 on December 12 


)Method of parsing string to date time

  • paser(String str): parse a date string into a date object. Note that the format of the string date should be correct, otherwise the parsing fails

  • Paser (string STR, datetimeformatter): parses the string according to the format passed in by the parameter


public void test06() {

    //Give a date string that meets the default format

    String dateStr = "2020-01-01";

    //Parse the date string into a date object. If the date string is year, month and day, LocalDate is used for parsing

    LocalDate parse = LocalDate.parse(dateStr);



    //Give a time, minute and second string that meets the requirements of the default format

    String dateTimeStr = "14:20:30";

    //Parse the hour, minute and second string into an hour, minute and second object

    LocalTime parse1 = LocalTime.parse(dateTimeStr);



    //Give a date, hour, minute and second string that meets the requirements of the default format

    String str = "2018-12-12T14:20:30";

    //Parses the date, hour, minute and second string into an hour, minute and second object

    LocalDateTime parse2 = LocalDateTime.parse(str);



    //Give a custom date, hour, minute and second format string

    String dateStr2 = "2020 December 12:13:14";

    //Give a custom parsing format

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy year MM month dd day HH:mm:ss");

    //Parse according to the specified format

    LocalDateTime parse3 = LocalDateTime.parse(dateStr2, formatter);



Output results








TemporalAdjuster interface - time regulator

All the date operations seen above are relatively direct. Sometimes, you need to perform more flexible and complex operations, such as adjusting the date to the next Sunday, the next working day, or the last day of the month. At this time, you need the time adjuster temporary adjuster, which can handle dates more flexibly. The temporary adjusters tool provides some general functions, and you can add your own functions.


public void testTemporalAdjuster() {

    LocalDate now =;

    //Specify Date

    //For some special dates, you can specify them through a tool class TemporalAdjusters

    //The first day of this month

    TemporalAdjuster temporalAdjuster = TemporalAdjusters.firstDayOfMonth();

    LocalDate with = now.with(temporalAdjuster);


    //Next weekend

    TemporalAdjuster next =;

    LocalDate with1 = now.with(next);



    LocalDate now1 =;

    //Custom date - next business day

    LocalDate with2 = now1.with(new TemporalAdjuster() {


        //Parameter nowDate the current date object

        public Temporal adjustInto(Temporal nowDate) {

            //Downward transformation

            LocalDate date = (LocalDate) nowDate;

            if (date.getDayOfWeek().equals(DayOfWeek.FRIDAY)) {

                LocalDate localDate = date.plusDays(3);

                return localDate;

            } else if (date.getDayOfWeek().equals(DayOfWeek.SATURDAY)) {

                LocalDate localDate = date.plusDays(2);

                return localDate;

            } else {

                LocalDate localDate = date.plusDays(1);

                return localDate;




    System.out.println("The next working day is:" + with2);


Output results




The next working day is 2020-12-14 

Duration class - a class used to calculate two "time" intervals

Duration represents a time period. Duration consists of two parts: seconds represents seconds and nanos represents nanoseconds. Their combination represents the length of time.

Because Duration represents a time period, the Duration class does not contain the now() static method. Note that Duration does not contain the attribute milliseconds.

Duration can only process two localtimes, localdatetime and zoneddatetime; If LocalDate is passed in, an exception will be thrown

Common API s:

  • Static method between(): calculates the interval between two times. The default is seconds

  • toDays(): convert time to days

  • toHours(): converts time to hours

  • To minutes(): converts time to minutes

  • To millis(): converts time to in milliseconds

  • toNanos(): converts time to nanosecond


public void test10() {

    //Interval for calculating time

    Instant start =;

    for (int i = 0; i < 100000; i++) {

        // System.out.println(i);


    Instant end =;

    Duration duration = Duration.between(start, end);

    long l = duration.toNanos();

    //Interval time

    System.out.println("Cycle time:" + l + "nanosecond");


Output results

Cycle time: 1000000 nanoseconds 

Period class - the class used to calculate the interval between two dates

Period is similar to duration in concept. The difference is that period is a time period measured by month, year and day. Duration is used to calculate two time intervals and period is used to calculate two date intervals, so the between() method can only receive parameters of LocalDate type.

  • Static method between(): calculates the interval between two dates

  • getYears(): get the year

  • getMonths(): get month

  • getDays(): get days


public void test11() {

    //Calculate the interval between two dates

    LocalDate birthday = LocalDate.of(2012, 12, 12);

    LocalDate now =;

    //How old, months and days have I been since I was born

    //Calculate the interval between two dates

    Period between = Period.between(birthday, now);

    int years = between.getYears();

    int months = between.getMonths();

    int days = between.getDays();

    System.out.println("The Mayan earth was wiped out" + years + "year" + months + "month" + days + "Oh, my God...");


Output results

The Mayan earth has been destroyed for 8 years, 0 months and 0 days... 

Instant timestamp class

java. time. An instantaneous point on the instant timeline, which carries the Unix timestamp with nanosecond accuracy, and its String toString() method is formatted based on ISO-8601. Instant does not host time zone information.

Method to get the object: now(): note that the default time zone is obtained by default, which is eight hours different from us (because we are in the East eight time zone)

How to set the offset: atOffset()

Method to obtain the system default time zone: atZone(): the parameter of the method is the number of a time zone (you can obtain the object of ZonedDateTime class through the time zone number class)

get series method

  • getEpochSecond(): get the second value from 1970-01-01 00:00:00 to the current time

  • Toepochmili(): get the millisecond value from 1970-01-01 00:00:00 to the current time

  • getNano(): convert the seconds of the current time obtained into nanoseconds

ofEpoch series method

  • ofEpochSecond(): adds seconds to the first year of the computer

  • Ofepochmili(): adds milliseconds to the first year of the computer


public void test09() {

    //  The millisecond value of the Instant timestamp class from 1970 - 01 - 01 00:00:00 to the current time

    Instant now =;

    System.out.println(now); //The default time zone is obtained, not the time zone of China

    //To get the current time zone, we can add an offset and return the date after the offset

    OffsetDateTime offsetDateTime = now.atOffset(ZoneOffset.ofHours(8));



    //Milliseconds from 1970 - 01 - 01 00:00:00 to the current time

    long l = System.currentTimeMillis();


    long time = new Date().getTime();


    //JDK1. 8. The millisecond value of the instant timestamp class from 1970 - 01 - 01 00:00:00 to the current time

    Instant now1 =;

    //Toepochmili(): the millisecond value from 1970 - 01 - 01 00:00:00 to the current time interval

    long l1 = now1.toEpochMilli();


    //Gets the second value from 1970 - 01 - 01 00:00:00 to the current time interval

    long epochSecond = now1.getEpochSecond();



    //Add the corresponding amount of time to the computer in the first year

    Date date = new Date(1000 * 60 * 60 * 24);


    //Now add the corresponding amount of time to the computer in the first year

    //5. The ofepochsecond() method adds seconds to the computer in the first year

    //Ofepochmili() adds milliseconds to the first year of the computer

    Instant instant = Instant.ofEpochMilli(1000 * 60 * 60 * 24);


    //The ofEpochSecond() method adds seconds to the computer in the first year

    Instant instant1 = Instant.ofEpochSecond(60 * 60 * 24);



Output results









Fri Jan 02 08:00:00 CST 1970



Clock - clock system

Clock is a clock system used to find the current time. You can use it to get the current date or time in a time zone. You can use clock to replace the old system Currenttimeinmillis() and timezone Getdefault() method.


public void testClock() {

    //System default time

    Clock clock = Clock.systemDefaultZone();


    //Universal coordinated time UTC

    Clock clock1 = Clock.systemUTC();

    //Get the current time through Clock

    System.out.println("The current time is:" + clock1.instant());

    //Gets the number of milliseconds corresponding to the clock, which is the same as system The output of currenttimemillis() is the same



    System.out.println(new Date(System.currentTimeMillis()).toString());

    //Add 6000 seconds to the clock and return to the new clock

    Clock clock2 = Clock.offset(clock1, Duration.ofSeconds(6000));

    //New York time

    Clock clock3 = Clock.system(ZoneId.of("America/New_York"));

    System.out.println("Current DateTime with NewYork clock: " +;



Output results


Current time: 2020-12-12T09:05:07.036Z



Sat Dec 12 17:05:07 CST 2020

Current DateTime with NewYork clock: 2020-12-12T04:05:07.040


ZonedDate, ZonedTime, ZonedDateTime - date time with time zone

The methods and usages of these three classes are basically the same as those of LocalDate, LocalTime and LocalDateTime, except that ZonedDate, ZonedTime and ZonedDateTime have specific time zones


)ZoneId - world time zone class

Java uses ZoneId to identify different time zones. A fixed offset of the time zone from the base UTC. ZoneOffset, a subclass of ZoneId, represents the time offset from the zero degree meridian in Greenwich, London, that is, the time difference.

Common API s:

  • getAvailableZoneIds(): get the collection of time zones in various parts of the world

  • systemDefault(): gets the ID of the system's default time zone

  • of(String zoneName): creates an object based on the time zone ID name of each region


public void test13() {

    //ZoneID world time zone class

    //Get time zone numbers around the world.

    Set<String> availableZoneIds = ZoneId.getAvailableZoneIds();

    for (String availableZoneId : availableZoneIds) {




    //Gets the default time zone number of the system

    ZoneId zoneId = ZoneId.systemDefault();


    //Get dates for other countries

    LocalDateTime now =;

    //Gets the date time of the specified time zone

    ZoneId zoneId1 = ZoneId.of("Europe/Monaco");

    ZonedDateTime zonedDateTime = now.atZone(zoneId1);  //Gets the current time in the specified time zone



    //Get the date of the region according to the time zone

    LocalDateTime now1 ="America/Phoenix"));  //Gets the current time in the specified time zone (without time zone information)



Output results


















DateTimeFormatter class - used to parse date strings and format date output

DateTimeFormatter is used to parse date string and format date output. The easiest way to create formatter is through DateTimeFormatter's static factory method and constant.

Before java8, we mainly used SimpleDateFormat for time formatting, while in java8, we mainly used DateTimeFormatter. In java8, some standard time formats are predefined, and we can directly convert time to standard time format

Common API s:

  • ofPattern("yyyy MM DD"): a static method that obtains objects in a given format

  • format(): formats the default format of a date object into a string of the specified format


public void test12() {

    // Class new SimpleDateFormat() for previously formatted dates

    //JDK1.8 DateTimeFormatter

    //Specifies the format static method ofPattern()

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    // DateTimeFormatter's own format method

    LocalDateTime now =;

    //Format the date object into a string

    String format = formatter.format(now);

    //The way just now is to use the formatting method of the date

    String format1 = now.format(formatter);




Output results

2020-12-12 17:28:50

2020-12-12 17:28:50 


)Formatted output & string parsing

java.time.format.DateTimeFormatter can format the output of TemporalAccessor types (including LocalDate, LocalTime, LocalDateTime and ZonedDateTime). At the same time, LocalDate, LocalTime, LocalDateTime and ZonedDateTime provide static parse methods for string parsing.

LocalDate, LocalTime, LocalDateTime, ZonedDateTime allow formatted output and string parsing based on the default format of the type.

|Type | example of default format|

| — | — |

| Instant | 2017-11-23T10:15:30.00Z |

| LocalDate | 2017-11-23 |

| LocalTime | 10:15:30 |

| LocalDateTime | 2017-11-23T10:15:30 |

| ZonedDateTime | 2017-11-23T10:15:30+01:00[Asia/Shanghai] |

Correct posture using SimpleDateFormat

Method 1: create new SimpleDateFormat instances where formatting needs to be performed, and use local variables to store SimpleDateFormat instances

public static String formatDate(Date date) {

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    return sdf.format(date);


This method may cause a large number of SimpleDateFormat instances to be created in a short time, such as parsing a string date in an excel table.

Method 2: in order to avoid creating a large number of SimpleDateFormat instances, we often consider setting SimpleDateFormat instances as static member variables and sharing SimpleDateFormat objects. In this case, you have to add synchronization to SimpleDateFormat.

private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

public static String formatDate(Date date) {

    synchronized (sdf) {

        return sdf.format(date);



The disadvantage of this method is also obvious, that is, it will cause parsing to be blocked in a high concurrency environment.

Method 3 (recommended): to have a good experience in a high concurrency environment, you can use ThreadLocal to limit that SimpleDateFormat can only be shared within threads, so as to avoid thread safety problems caused by multithreading.

private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>() {


    protected DateFormat initialValue() {

        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");



public static String formatDate(Date date) {

    return threadLocal.get().format(date);


Mutual conversion of Java8 Date time class and Date class

In the conversion, we need to note that before java8, Date contains Date and time, while LocalDate only contains Date and LocalTime only contains time. Therefore, in the conversion with Date, it is bound to lose Date or time or use the start time. If you switch to LocalDateTime, there is no information error.


)Date and Instant are converted to each other


public void test18() {

    //Date and Instant are converted to each other

    Instant instant  =;

    Date date = Date.from(instant);


    Instant instant2 = date.toInstant();



Output results

Sat Dec 12 21:18:13 CST 2020



)Date and LocalDateTime are converted to each other


public void test19() {

    //Date - LocalDateTime

    Date date = new Date();

    System.out.println("current date: " + date);

    LocalDateTime localDateTime1 = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();

    System.out.println("localDateTime1: " + localDateTime1);

    LocalDateTime localDateTime2 = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());

    System.out.println("localDateTime2: " + localDateTime2);

    //LocalDateTime - Date

    LocalDateTime localDateTime =;

    System.out.println("localDateTime: " + localDateTime);

    Date date1 = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());

    System.out.println("date1: " + date1);


Output results

current date: Sat Dec 12 21:27:47 CST 2020

localDateTime1: 2020-12-12T21:27:47.592

localDateTime2: 2020-12-12T21:27:47.592

localDateTime: 2020-12-12T21:27:47.652

date1: Sat Dec 12 21:27:47 CST 2020 


)Date and LocalDate are converted to each other


public void test20() {

Keywords: Java Back-end Interview Programmer

Added by camdenite on Fri, 17 Dec 2021 00:17:09 +0200