Java 8 date processing

Java 8 has a new date and time API. In this tutorial, we will learn how to use the new API with some simple examples.

Java has long been criticized by the community for the way it handles dates, calendars, and times, and the mutable type of java.util.Date and the non-thread-safe nature of SimpleDateFormat make its use very limited.

The new API is based on the ISO standard calendar system, and all classes under the java.time package are immutable and thread safe.

Serial number The name of the class describe
1 Instant The time stamp
2 Duration Duration, time difference
3 LocalDate Include only the date, for example: 2018-02-05
4 LocalTime Contains only the time, such as 23:12:10
5 LocalDateTime Contains the date and time, for example: 2018-02-05 23:14:21
6 Period Period of time
7 ZoneOffset Time zone offset, for example, +8
8 ZonedDateTime Time in the time zone
9 Clock For example, get the current time in New York, USA
10 java.time.format.DateTimeFormatter Time formatting

Example 1: Get today’s date in Java 8

In Java 8, LocalDate is used to indicate the date of the day. Unlike java.util.Date, it has only the Date, not the time. Use this class when you only need to represent dates.

package com.shxt.demo02;

import java.time.LocalDate;

public class Demo01 {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        System.out.println("Today's date :"+today); }}/* Run result: today's date :2018-02-05 */
Copy the code

Example 2: Get the year, month, and day information in Java 8

package com.shxt.demo02;

import java.time.LocalDate;

public class Demo02 {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        int year = today.getYear();
        int month = today.getMonthValue();
        int day = today.getDayOfMonth();

        System.out.println("year:"+year);
        System.out.println("month:"+month);
        System.out.println("day:"+day); }}Copy the code

Example 3: Processing specific dates in Java 8

We created the date very easily with the static factory method now(). You can also create any date by calling another useful factory method, localdate.of (). This method takes the year, month, and day as arguments and returns the corresponding instance of LocalDate. The advantage of this approach is that you don’t make the old API design mistakes, such as year starting at 1900, month starting at 0, etc.

package com.shxt.demo02;

import java.time.LocalDate;

public class Demo03 {
    public static void main(String[] args) {
        LocalDate date = LocalDate.of(2018.2.6);
        System.out.println("Custom date :"+date); }}Copy the code

Example 4: Determining whether two dates are equal in Java 8

package com.shxt.demo02;

import java.time.LocalDate;

public class Demo04 {
    public static void main(String[] args) {
        LocalDate date1 = LocalDate.now();

        LocalDate date2 = LocalDate.of(2018.2.5);

        if(date1.equals(date2)){
            System.out.println("Equal time.");
        }else{
            System.out.println("Time is not equal."); }}}Copy the code

Example 5: Check for periodic events like birthdays in Java 8

package com.shxt.demo02;

import java.time.LocalDate;
import java.time.MonthDay;

public class Demo05 {
    public static void main(String[] args) {
        LocalDate date1 = LocalDate.now();

        LocalDate date2 = LocalDate.of(2018.2.6);
        MonthDay birthday = MonthDay.of(date2.getMonth(),date2.getDayOfMonth());
        MonthDay currentMonthDay = MonthDay.from(date1);

        if(currentMonthDay.equals(birthday)){
            System.out.println("It's your birthday");
        }else{
            System.out.println("It's not your birthday yet."); }}}Copy the code

As long as the date matches the birthday, a congratulatory message is printed regardless of the year. You can integrate the program into the system clock to see if you get a birthday alert, or write a unit test to check if the code is running correctly.

Example 6: Get the current time in Java 8

package com.shxt.demo02;

import java.time.LocalTime;

public class Demo06 {
    public static void main(String[] args) {
        LocalTime time = LocalTime.now();
        System.out.println("Get the current time, without date :"+time); }}Copy the code

You can see that the current time contains only time information, no date

Example 7: Get the current time in Java 8

It is common to calculate future time by adding hours, minutes, and seconds. In addition to the benefits of type-invariance and thread-safety, Java 8 also provides a better plusHours() method instead of add() and is compatible. Note that these methods return a completely new instance of LocalTime, which must be assigned to a variable because of its immutability.

package com.shxt.demo02;

import java.time.LocalTime;

public class Demo07 {
    public static void main(String[] args) {
        LocalTime time = LocalTime.now();
        LocalTime newTime = time.plusHours(3);
        System.out.println("The time after three hours is :"+newTime); }}Copy the code

Example 8: How does Java 8 calculate a date one week from now

Similar to the previous example calculating the time after 3 hours, this example will calculate the date after one week. The LocalDate date contains no time information. Its plus() method is used to add days, weeks, and months, and the ChronoUnit class declares these units of time. Since LocalDate is also an immutable type, it must be assigned to a variable after return.

package com.shxt.demo02;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

public class Demo08 {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        System.out.println("Today's date is :"+today);
        LocalDate nextWeek = today.plus(1, ChronoUnit.WEEKS);
        System.out.println("A week from now :"+nextWeek); }}Copy the code

You can see that the new date is 7 days from that date, which is one week. You can add a month, a year, an hour, a minute, or even a century in the same way. For more options, see the ChronoUnit class in the Java 8 API

Example 9:Java 8 calculates a date one year ago or one year from now

Minus () method is used to calculate the date one year ago

package com.shxt.demo02;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

public class Demo09 {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();

        LocalDate previousYear = today.minus(1, ChronoUnit.YEARS);
        System.out.println("Date one year ago:" + previousYear);

        LocalDate nextYear = today.plus(1, ChronoUnit.YEARS);
        System.out.println("A year from now :"+nextYear); }}Copy the code

Example 10:Java 8’s Clock class

Java 8 adds a Clock class to get the current timestamp, or date and time information under the current time zone. Previously used System. CurrentTimeInMillis () and TimeZone. GetDefault () places available Clock is replaced.

package com.shxt.demo02;

import java.time.Clock;

public class Demo10 {
    public static void main(String[] args) {
        // Returns the current time based on your system clock and set to UTC.
        Clock clock = Clock.systemUTC();
        System.out.println("Clock : " + clock.millis());

        // Returns time based on system clock zone
        Clock defaultClock = Clock.systemDefaultZone();
        System.out.println("Clock : "+ defaultClock.millis()); }}Copy the code

Example 11: How can I use Java to determine if a date is earlier or later than another date

Another common operation at work is how to determine if a given date is greater than or less than a certain day. In Java 8, the LocalDate class has two classes of methods, isBefore() and isAfter(), for comparing dates. When the isBefore() method is called, returns true if the given date is less than the current date.

package com.shxt.demo02;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;


public class Demo11 {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();

        LocalDate tomorrow = LocalDate.of(2018.2.6);
        if(tomorrow.isAfter(today)){
            System.out.println("After the date :"+tomorrow);
        }

        LocalDate yesterday = today.minus(1, ChronoUnit.DAYS);
        if(yesterday.isBefore(today)){
            System.out.println("Previous date :"+yesterday); }}}Copy the code

Example 12: Processing time zones in Java 8

Java 8 separates not only date and time, but also time zones. There are now a series of separate classes such as ZoneId to deal with specific time zones, and the ZoneDateTime class to represent the time in a specific time zone. This was done by the GregorianCalendar class before Java 8. The following example shows how to convert time in one time zone to time in another.

package com.shxt.demo02;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class Demo12 {
    public static void main(String[] args) {
        // Date and time with timezone in Java 8
        ZoneId america = ZoneId.of("America/New_York");
        LocalDateTime localtDateAndTime = LocalDateTime.now();
        ZonedDateTime dateAndTimeInNewYork  = ZonedDateTime.of(localtDateAndTime, america );
        System.out.println("Current date and time in a particular timezone : "+ dateAndTimeInNewYork); }}Copy the code

Example 13: How do you represent a fixed date such as the expiration of a credit card, the answer is in YearMonth

Similar to the example of MonthDay to check for duplicate events, YearMonth is another combination class that represents credit card expiration dates, FD expiration dates, futures option expiration dates, and so on. You can also use this class to find out how many days there are in the month. The lengthOfMonth() method of the YearMonth instance returns the number of days for the month, which is useful in determining whether February has 28 or 29 days.

package com.shxt.demo02;

import java.time.*;

public class Demo13 {
    public static void main(String[] args) {
        YearMonth currentYearMonth = YearMonth.now();
        System.out.printf("Days in month year %s: %d%n", currentYearMonth, currentYearMonth.lengthOfMonth());
        YearMonth creditCardExpiry = YearMonth.of(2019, Month.FEBRUARY);
        System.out.printf("Your credit card expires on %s %n", creditCardExpiry); }}Copy the code

Example 14: How do I check leap years in Java 8

package com.shxt.demo02;

import java.time.LocalDate;

public class Demo14 {
    public static void main(String[] args) {
        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: Calculate the number of days and months between two dates

A common date operation is to calculate the number of days, weeks, or months between two dates. In Java 8, you can use the java.time.Period class to do the calculation. In the following example, we calculate the number of months between that day and a future day.

package com.shxt.demo02;

import java.time.LocalDate;
import java.time.Period;

public class Demo15 {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();

        LocalDate java8Release = LocalDate.of(2018.12.14);

        Period periodToNextJavaRelease = Period.between(today, java8Release);
        System.out.println("Months left between today and Java 8 release : "+ periodToNextJavaRelease.getMonths() ); }}Copy the code

Example 16: Get the current timestamp in Java 8

The Instant class has a static factory method now() that returns the current timestamp, as shown below:

package com.shxt.demo02;

import java.time.Instant;

public class Demo16 {
    public static void main(String[] args) {
        Instant timestamp = Instant.now();
        System.out.println("What is value of this instant "+ timestamp.toEpochMilli()); }}Copy the code

The timestamp information contains both the Date and time, much like java.util.Date. In fact, the Instant class is equivalent to the Date class before Java 8. You can use the conversion methods of the Date and Instant classes to convert each other. For example: Date.from(Instant) converts Instant to java.util.Date, and date.toinstant () converts Date toInstant.

Example 17: How do I use the predefined formatting tools to parse or format dates in Java 8

package com.shxt.demo02;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class Demo17 {
    public static void main(String[] args) {
        String dayAfterTommorrow = "20180205";
        LocalDate formatted = LocalDate.parse(dayAfterTommorrow,
                DateTimeFormatter.BASIC_ISO_DATE);
        System.out.println(dayAfterTommorrow+"The formatted date is:"+formatted); }}Copy the code

Example 18: String transfer date type

package com.shxt.demo02;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Demo18 {
    public static void main(String[] args) {
        LocalDateTime date = LocalDateTime.now();

        DateTimeFormatter format1 = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
		// The date is a string
        String str = date.format(format1);

        System.out.println("Convert date to string :"+str);

        DateTimeFormatter format2 = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
		// String transfer date
        LocalDate date2 = LocalDate.parse(str,format2);
        System.out.println("Date type :"+date2); }}Copy the code