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

@Test

public void test07() {

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

    LocalDateTime now = LocalDateTime.now();

    System.out.println(now);

    //You can add time to the current date

    LocalDateTime newDate = now.plusYears(1);

    int year = newDate.getYear();

    System.out.println(year);



    System.out.println("================================");

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

    LocalDate now1 = LocalDate.now();

    System.out.println(now1);

    LocalDate newDate2 = now1.minusDays(10);

    int dayOfMonth = newDate2.getDayOfMonth();

    System.out.println(dayOfMonth);

} 

Output results

2020-12-12T16:12:43.228

2021

================================

2020-12-12

2 

[](

)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

@Test

public void test08() {

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

    LocalDate now2 = LocalDate.now();

    System.out.println(now2);

    LocalDate localDate = now2.withYear(2014);

    System.out.println(localDate);



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

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

    System.out.println(with);

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

    System.out.println(with1);



    //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));

    System.out.println(with2);

} 

Output results

2020-12-12

2014-12-12

2020-12-01

2021-01-01

2020-12-11 

[](

)Method to format a date as a string

  • format(): format string
@Test

public void test03() {

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

    LocalDateTime now = LocalDateTime.now();



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

    System.out.println(now);



    //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);

    System.out.println(dateStr);

} 

Output results

2020-12-12T16:06:12.705

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

@Test

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);

    System.out.println(parse);



    System.out.println("===========================================");

    //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);

    System.out.println(parse1);



    System.out.println("=========================================");

    //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);

    System.out.println(parse2);



    System.out.println("========================================");

    //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);

    System.out.println(parse3);

} 

Output results

2020-01-01

===========================================

14:20:30

=========================================

2018-12-12T14:20:30

========================================

2020-12-12T12:13:14 

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.

@Test

public void testTemporalAdjuster() {

    LocalDate now = 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);

    System.out.println(with);

    //Next weekend

    TemporalAdjuster next = TemporalAdjusters.next(DayOfWeek.SUNDAY);

    LocalDate with1 = now.with(next);

    System.out.println(with1);

    System.out.println("===================================");



    LocalDate now1 = LocalDate.now();

    //Custom date - next business day

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

        @Override

        //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

2020-12-01

2020-12-13

===================================

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

@Test

public void test10() {

    //Interval for calculating time

    Instant start = Instant.now();

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

        // System.out.println(i);

    }

    Instant end = Instant.now();

    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

@Test

public void test11() {

    //Calculate the interval between two dates

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

    LocalDate now = 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

@Test

public void test09() {

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

    Instant now = 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));

    System.out.println(offsetDateTime);

    System.out.println("===========================");



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

    long l = System.currentTimeMillis();

    System.out.println(l);

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

    System.out.println(time);



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

    Instant now1 = Instant.now();



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

    long l1 = now1.toEpochMilli();

    System.out.println(l1);



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

    long epochSecond = now1.getEpochSecond();

    System.out.println(epochSecond);



    System.out.println("==========================");

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

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

    System.out.println(date);



    //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);

    System.out.println(instant);



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

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

    System.out.println(instant1);

} 

Output results

2020-12-12T08:48:46.480Z

2020-12-12T16:48:46.480+08:00

===========================

1607762926539

1607762926540

1607762926540

1607762926

==========================

Fri Jan 02 08:00:00 CST 1970

1970-01-02T00:00:00Z

1970-01-02T00:00:00Z 

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.

@Test

public void testClock() {

    //System default time

    Clock clock = Clock.systemDefaultZone();

    System.out.println(clock.instant().toString());



    //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(clock1.millis());

    System.out.println(System.currentTimeMillis());

    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: " + LocalDateTime.now(clock3));

    System.out.println(clock3.millis());

} 

Output results

2020-12-12T09:05:07.025Z

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

1607763907036

1607763907036

Sat Dec 12 17:05:07 CST 2020

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

1607763907041 

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

@Test

public void test13() {

    //ZoneID world time zone class

    //Get time zone numbers around the world.

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

    for (String availableZoneId : availableZoneIds) {

        System.out.println(availableZoneId);

    }



    System.out.println("=====================");

    //Gets the default time zone number of the system

    ZoneId zoneId = ZoneId.systemDefault();

    System.out.println(zoneId);



    //Get dates for other countries

    LocalDateTime now = 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

    System.out.println(zonedDateTime);



    System.out.println("=====================");

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

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

    System.out.println(now1);

} 

Output results

America/Toronto

Asia/Singapore

Australia/Lindeman

America/Los_Angeles

SystemV/EST5EDT

Pacific/Majuro

America/Argentina/Buenos_Aires

Europe/Nicosia

Pacific/Guadalcanal

Europe/Athens

US/Pacific

Europe/Monaco

=====================

Asia/Shanghai

2020-12-12T20:56:27.214+01:00[Europe/Monaco]

=====================

2020-12-12T05:56:27.225 

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

@Test

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 = 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);

    System.out.println(format);

    System.out.println(format1);

} 

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>() {

    @Override

    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

@Test

public void test18() {

    //Date and Instant are converted to each other

    Instant instant  = Instant.now();

    Date date = Date.from(instant);

    System.out.println(date);



    Instant instant2 = date.toInstant();

    System.out.println(instant2);

} 

Output results

Sat Dec 12 21:18:13 CST 2020

2020-12-12T13:18:13.129Z 

[](

)Date and LocalDateTime are converted to each other

@Test

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 = LocalDateTime.now();

    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

@Test

public void test20() {



Keywords: Java Back-end Interview Programmer

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