Practice of 18 Java 8 Date Processing

  • Example 1: Get today's date in Java 8

  • Example 2: Getting year, month, day information in Java 8

  • Example 3: Processing a specific date in Java 8

  • Example 4: Judging whether two dates are equal in Java 8

  • Example 5: Checking for periodic events like birthdays in Java 8

  • Example 6: Getting the current time in Java 8

  • Example 7: Getting the current time in Java 8

  • Example 8: How Java 8 calculates the date in a week

  • Example 9:Java 8 calculates the date a year ago or after

  • Clock clock class for example 10:Java 8

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

  • Example 12: Processing time zones in Java 8

  • Example 13: How to represent a fixed date such as credit card expiration, the answer is in YearMonth

  • Example 14: How to check leap years in Java 8

  • Example 15: Calculate the number of days and months between two dates

  • Example 16: Get the current timestamp in Java 8

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

  • Example 18: String Interchange Date Type

Java 8 Date Processing

Java 8 has introduced a new Date Time API, in which we will learn how to use the new API through a few simple examples.

The way Java handles dates, calendars, and times has long been criticized by the community for making java.util.Date a variable type and the non-threaded security of SimpleDateFormat very restrictive.

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

number The name of the class describe
1 Instant time stamp
2 Duration Duration, time difference
3 LocalDate Only include dates, such as 2018-02-05
4 LocalTime Only include time, such as 23:12:10
5 LocalDateTime Contains date and time, such as: 2018-02-05 23:14:21
6 Period Time slot
7 ZoneOffset Time zone offset, such as: +8:00
8 ZonedDateTime Time with Time Zone
9 Clock Clocks, such as getting the current time in New York, USA
10 java.time.format.DateTimeFormatter Time Formatting

Example 1: Get today's date in Java 8

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

package com.shxt.demo02;

import java.time.LocalDate;

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

Example 2: Getting year, month, day information in Java 8

package com.shxt.demo02;

import java.time.LocalDate;

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

    }
}

Example 3: Processing a specific date in Java 8

The current date is easily created by the static factory method now(), and you can also call another useful factory method, LocalDate.of(), to create any date by passing in parameters of year, month, and day to return the corresponding LocalDate instance.The advantage of this approach is that you no longer make design errors with older API s, such as starting the year in 1900, starting the month in 0, and so on.

package com.shxt.demo02;

import java.time.LocalDate;

publicclass Demo03 {
    public static void main(String[] args) {
        LocalDate date = LocalDate.of(2018,2,6);
        System.out.println("Custom Date:"+date);
    }
}

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

package com.shxt.demo02;

import java.time.LocalDate;

publicclass 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 inequality");
        }

    }
}

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

package com.shxt.demo02;

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

publicclass 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("Your birthday hasn't arrived yet");
        }

    }
}


As long as the day matches the birthday, congratulations will be printed in any year.You can incorporate the program into your system clock to see if you are reminded on your birthday, or write a unit test to check if the code is working correctly.

Example 6: Getting the current time in Java 8

package com.shxt.demo02;

import java.time.LocalTime;

publicclass Demo06 {
    public static void main(String[] args) {
        LocalTime time = LocalTime.now();
        System.out.println("Get the current time,No date included:"+time);

    }
}


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

Example 7: Getting 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 constant type and thread security, Java 8 provides a better plusHours() method to replace add() and is compatible.Note that these methods return a completely new LocalTime instance, since they are not mutable, they must be assigned with a variable after returning.

package com.shxt.demo02;

import java.time.LocalTime;

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

    }
}


Example 8: How Java 8 calculates the date in a week

Similar to the previous example, which calculates the time after three hours, this example calculates the date after one week.The LocalDate date does not contain time information, and its plus() method adds days, weeks, and months, which are declared by the ChronoUnit class.Since LocalDate is also an invariant type, you must assign it with a variable after returning.

package com.shxt.demo02;

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

publicclass 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("Date after one week is:"+nextWeek);

    }
}

You can see that the new date is seven days from that day, or one week.You can add a month, a year, an hour, a minute, or even a century in the same way, and more options are available for viewing the ChronoUnit class in the Java 8 API

Example 9:Java 8 calculates the date a year ago or after

Calculate the date a year ago using the minus() method

package com.shxt.demo02;

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

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

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

        LocalDate nextYear = today.plus(1, ChronoUnit.YEARS);
        System.out.println("Date after one year:"+nextYear);

    }
}

Clock clock class for example 10:Java 8

Java 8 added a Clock clock class to get time stamps at that time, or date-time information in the current time zone.Previous uses of System.currentTimeInMillis() and TimeZone.getDefault() can be replaced with Clock.

package com.shxt.demo02;

import java.time.Clock;

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

    }
}

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

Another common practice in work is how to tell if a given date is greater or less than a certain day?In Java 8, the LocalDate class has two methods, isBefore(), and isAfter(), for comparing dates.

When calling the isBefore() method, 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;


publicclass 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("Date after:"+tomorrow);
        }

        LocalDate yesterday = today.minus(1, ChronoUnit.DAYS);
        if(yesterday.isBefore(today)){
            System.out.println("Date before:"+yesterday);
        }
    }
}

Example 12: Processing time zones in Java 8

Java 8 separates not only date and time, but also time.There are now a series of separate classes, such as ZoneId, that handle specific time zones, and ZoneDateTime classes that represent the time in a time zone.This was done by the Gregorian Calendar 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;

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

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

Similar to the MonthDay example of checking 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 get the total number of days in the month. The lengthOfMonth() method of the YearMonth instance returns the number of days in the month, which is useful in determining whether there are 28 or 29 days in February.

package com.shxt.demo02;

import java.time.*;

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

Example 14: How to check leap years in Java 8

package com.shxt.demo02;

import java.time.LocalDate;

publicclass 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");
        }

    }
}

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.You can use the java.time.Period class for calculations in Java 8.In the example below, 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;

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


    }
}

Example 16: Get the current timestamp in Java 8

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

package com.shxt.demo02;

import java.time.Instant;

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

Timestamp information contains both date and time, much like java.util.Date.In fact, the Instant class is really the same as the Date class before Java 8, and you can use the Date and Instant classes'respective conversion methods to convert each other

For example, Date.from(Instant) converts an Instant to java.util.Date, and Date.toInstant() converts a Date class to an Instant class.

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

package com.shxt.demo02;

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

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

Example 18: String Interchange Date Type

package com.shxt.demo02;

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

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

        DateTimeFormatter format1 = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
		//Date to String
        String str = date.format(format1);

        System.out.println("Date converted to string:"+str);

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

    }
}

 

51 original articles published. 20% praised. 70,000 visits+
Private letter follow

Keywords: Java less

Added by banks1850 on Fri, 06 Mar 2020 03:54:55 +0200