Recently, we need to deal with date and time frequently in the project. After comprehensive consideration, we choose to use the new date and time API of Java8 in the process of processing. In order to use it quickly in the future development, and to provide convenience for the masses of digging friends, we have made a sort of arrangement now.

This article is divided into two parts. The first part introduces the main Java8 date and time apis, and the second part shows the usage scenarios of each major API.

Introduction to Java8 main date and time apis

1,LocalDate

LocalDate abstracts the representation of a LocalDate, which is thread-safe because it is immutable. It overwrites the toString() method and returns the date in the format yyyy-mm-dd.

2,LocalDateTime

LocalDateTime (2020-05-24T13:04:30.197) is a thread-safe combination of LocalDate and LocalTime (2020-05-24T13:04:30.197).

3,LocalTime

LocalTime abstracts a representation of the LocalTime (not including dates) in thread-safe format :13:07:32.659;

4,Instant

Instant abstracts the representation of the timestamp. When representing the current timestamp, it contains the date and time (based on UTC time) in the format of 2020-05-24T05:14:44.899z.

5,ZonedDateTime

A complete date-time containing the time zone, offset in UTC; Format example :2020-05-25T17:16:18.475+08:00[Asia/Shanghai];

6,ZoneOffset

Represents a fixed zone offset from the UTC time zone. Changes to the zone offset caused by DAYLIGHT saving time are not tracked;

Application Scenario Example

Example 1, get the date of the day

LocalDate now = LocalDate.now();
// Execution result :2020-05-25
Copy the code

Example 2: Obtain the LocalDate based on the specific year/month/day value

// Get LocalDate based on the year/month/day value
LocalDate.of(2018.11.30);  
// Get LocalDate based on the NTH day of a year
LocalDate.ofYearDay(2018.300);
Copy the code

Example 3, get the date information corresponding to the current year based on today’s date

LocalDate now = LocalDate.now();
now.getYear(); // Today corresponds to the year
now.getMonthValue(); // month (numeric representation, starting from 1)
now.getMonth(); // Month (enum)
now.getDayOfMonth(); // Date (starting from 1)
now.getDayOfYear(); // The day of the year (starting from 1)
now.getDayOfWeek(); / / week
now.lengthOfYear(); // Number of days in the current year
now.lengthOfMonth(); // Days of the month
now.toEpochDay(); // The number of days off from the time era (January 1, 1970). A negative number indicates the number of days prior to the time era
now.isLeapYear();// Is this a leap year
Copy the code

Example 4, date/week/month/year calculation based on today’s date

System.out.println("Addition operation");
System.out.println("Current:" + LocalDate.now());
System.out.println("Plus 1 day:" + LocalDate.now().plusDays(1));
System.out.println("+ 1 week:" + LocalDate.now().plusWeeks(1));
System.out.println("Plus 1 month:" + LocalDate.now().plusMonths(1));
System.out.println("Plus 1 year:" + LocalDate.now().plusYears(1));
System.out.println("Subtraction");
System.out.println("Current:" + LocalDate.now());
System.out.println("Minus 1 day:" + LocalDate.now().minusDays(1));
System.out.println("Minus 1 week:" + LocalDate.now().minusWeeks(1));
System.out.println("Minus 1 month:" + LocalDate.now().minusMonths(1));
System.out.println("Minus 1 year:" + LocalDate.now().minusYears(1));
Copy the code

Example 5, two date comparisons based on LocalDate

System.out.println("The day:" + LocalDate.now());
System.out.println("Was it before the day:" + LocalDate.now().minusDays(1).isBefore(LocalDate.now()));
System.out.println("Whether after that day:" + LocalDate.now().plusDays(1).isAfter(LocalDate.now()));
System.out.println("On the same day:" + LocalDate.now().isEqual(LocalDate.now()));
Copy the code

In example 6,LocalDate is converted to LocalDateTime

// The incoming time,h(hours) must be within 0~23,m(minutes) must be within 0~59, and s(seconds) must be within 0~59
LocalDate now = LocalDate.now();
System.out.println(now.atTime(10.11));// 2020-05-25T10:11
System.out.println(now.atTime(10.11.11)); // 2020-05-25T10:11:11
System.out.println(now.atTime(10.11.12.100000000));/ / the T10:2020-05-25 and 100
Copy the code

Example 7. How do I check for duplicate events, such as birthdays/monthly payment dates

LocalDate dateOfBirth = LocalDate.of(2021.01.14);
MonthDay birthday = MonthDay.of(dateOfBirth.getMonth(), dateOfBirth.getDayOfMonth());
MonthDay currentMonthDay = MonthDay.from(LocalDate.now());
if(currentMonthDay.equals(birthday)){
System.out.println("Many Many happy returns of the day !!");
}else{
System.out.println("Sorry, today is not your birthday");
}
Copy the code

Example 8. How do I get the current time

System.out.println(LocalDateTime.now()); / / date
System.out.println(LocalTime.now()); // No date
Copy the code

Example 9, calculation based on current time (e.g., get the time yesterday/tomorrow/one week from now)

LocalDateTime now = LocalDateTime.now();
System.out.println(now.plusSeconds(1));/ / 1 s after
System.out.println(now.plusMinutes(1));/ / after 1 min
System.out.println(now.plusHours(1));/ / 1 h after
System.out.println(now.plusDays(1));/ / 1 days
System.out.println(now.plusWeeks(1));/ / 1 weeks later
System.out.println(now.plusMonths(1));/ / 1 month later
System.out.println(now.plusYears(1));/ / 1 years later
// Count past time (subtraction)
System.out.println(now.minusSeconds(1));/ / 1 s before
/ /... Look at a similar addition operation
Copy the code

Example 10, the zero-point time and the last time calculated based on the current LocalDateTime

// Midnight of the day
System.out.println(LocalDateTime.of(LocalDate.now(), LocalTime.MIN));
// The last time of the day
System.out.println(LocalDateTime.of(LocalDate.now(), LocalTime.MAX));
// Get the Monday midnight time
System.out.println(LocalDateTime.of(LocalDate.now().with(DayOfWeek.MONDAY), LocalTime.MIN));
// Get last Monday's midnight time
System.out.println(LocalDateTime.of(LocalDate.now().with(DayOfWeek.MONDAY).minusWeeks(1),LocalTime.MIN));
// Get the first midnight of the month
System.out.println(LocalDate.of(LocalDate.now().getYear(), LocalDate.now().getMonth(), 1));
// Get the last time of the last day of the last month
System.out.println(LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.lastDayOfMonth()).minusMonths(1), LocalTime.MAX));
Copy the code

For example 11, Clock is used

Clock clock = Clock.systemUTC();
System.out.println(clock.instant());// Get an Instant value based on utc time
System.out.println(clock.millis());// Gets the current millisecond value based on utc time
Clock c1 = Clock.tick(clockDuration.ofSeconds(5));// Get a tick Clock with 5 seconds between ticks
Copy the code

Example 12, handling time transitions between different time zones

Converts the local time to the corresponding time in another time zone

ZoneId america = ZoneId.of("America/New_York");// New York time
LocalDateTime localDateTime = LocalDateTime.now();
ZonedDateTime dateAndTimeInNewYork = ZonedDateTime.of(localDateTime, america );
System.out.println("date and time in a particular timezone : " + dateAndTimeInNewYork);
Copy the code

Example 13, representing a fixed date, such as when a credit card expires

YearMonth can easily obtain the date of a specified year, such as the number of days in February of a year, and quickly determine whether it is a leap month, as shown in the following example:

YearMonth currentYearMonth = YearMonth.now();
// Get the current YearMonth example and the number of days in the current month
System.out.printf("Days in month year %s: %d%n", currentYearMonth, currentYearMonth.lengthOfMonth());
// Get the YearMonth of February 2108
YearMonth creditCardExpiry = YearMonth.of(2018, Month.FEBRUARY);
// Get the last day of February 2108
System.out.println(creditCardExpiry.atEndOfMonth());
// Get the second day of February 2108
System.out.println(creditCardExpiry.atDay(2));
Copy the code

Example 14, check leap years

LocalDate today = LocalDate.now();
if(today.isLeapYear()){ 
    System.out.println("This year is Leap year"); 
}else { 
    System.out.println("2018 is not a Leap year"); 
}
Copy the code

Example 15, how many months/days are contained between two dates

This can be done with the java.time.Period class, as shown in the following example:

LocalDate today = LocalDate.now();
LocalDate everDay = LocalDate.of(2016, Month.MARCH, 14);
Period period = Period.between(everDay, today);
// The current date corresponds to the number of years/months/days of the previous date
System.out.printf("year span is:%s; month span is:%s; date span is:%s",period.getYears(),period.getMonths(),period.getDays()); Note :Period can only count the number of days in the same month and the number of months in the same year. Can use the following demo validation: DateTimeFormatter formatter. = DateTimeFormatter ofPattern ("yyyy-MM-dd");
LocalDate date1 = LocalDate.parse("2020-05-12", formatter);
LocalDate date2 = LocalDate.parse("2021-05-13",formatter);
// Calculate the date interval
int period = Period.between(date1,date2).getDays();
System.out.println(period); // The result is 1!
Copy the code

Example 16, get the current timestamp

Instant timeStamp = Instant.now();
System.out.printf("current timeStamp is:%s",timeStamp);
Copy the code

Example 17, timestamp (Instant) andjava.util.DateConversion between

Date date = Date.from(Instant.now());
Instant instant = date.toInstant();
Copy the code

Example 18, use a formatter to parse/format the date

Before Java8, the SimpleDateFormat class was used to format dates. However, this class is not thread-safe and requires thread-safe control. In Java8, DateTimeFormatter formatter can easily format dates and times Parsed without worrying about thread safety, it can be formatted using either predefined or custom formats, as shown in the following usage example

// Base ISO date
String date = "20140116";
DateTimeFormatter dateFormatter = DateTimeFormatter.BASIC_ISO_DATE;
System.out.println(LocalDate.parse(date,dateFormatter));
// Iso date and time with time zone
String dateTime = "2011-12-03T10:15:30";
DateTimeFormatter isoDateTime = DateTimeFormatter.ISO_DATE_TIME;
System.out.println(LocalDateTime.parse(dateTime, isoDateTime));

String dateTime = "The 2018-12-03 10:15:30";
Parse the date string using a custom formatter
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dHH:mm:ss");
System.out.println(LocalDateTime.parse(dateTime, timeFormatter));
// Use custom formatters to format dates and times
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dHH:mm:ss");
String dateTime = now.format(timeFormatter);
Copy the code