Kill Date. Java8 LocalDate smells good

brief introduction

With lambda expressions, stream s and a series of minor optimizations, Java 8 has launched a new date and time API.

The deficiency of Java in dealing with date, calendar and time: Java util. Date is set as a variable type, and SimpleDateFormat's non thread safety makes its application very limited. Then add new features to java8.

One of the many benefits of the new API is that it defines the concept of date and time, such as instant, duration, date, time, time zone and period.

At the same time, it inherits the time processing method of Joda library according to human language and computer parsing. Different from the old version, the new API is based on the ISO standard calendar system, Java All classes under the time package are immutable and thread safe.

Key class

  • Instant: instantaneous instance.
  • LocalDate: local date, excluding specific time. For example, January 14, 2014 can be used to record birthdays, anniversaries, joining dates, etc.
  • LocalTime: local time, excluding date.
  • LocalDateTime: combines date and time, but does not contain time difference and time zone information.
  • ZonedDateTime: the most complete date and time, including the time zone and the time difference relative to UTC or Greenwich.

The new API also introduces ZoneOffSet and ZoneId classes, making it easier to solve the time zone problem. DateTimeFormatter for parsing and formatting time

Classes are also completely redesigned.

actual combat

In the tutorial, we will learn how to use the new API through some simple examples, because only using it in actual projects is the fastest way to learn new knowledge and new technologies.

1. Get the current date

LocalDate in Java 8 is used to represent the date of the day. And Java util. Different from date, it only has date and does not contain time. Use this class when you only need to represent dates.

//Get today's date
public void getCurrentDate(){
    LocalDate today = LocalDate.now();
    System.out.println("Today's Local date : " + today);

    //This is for comparison
    Date date = new Date();
    System.out.println(date);
}

The above code creates the Date of the day without time information. The printed Date format is very friendly. Unlike the Date class, it prints a pile of unformatted information.

2. Obtain year, month and day information

LocalDate provides a shortcut to get year, month and day. Its example also contains many other date attributes. By calling these methods, you can easily get the required date information without relying on Java as before util. Calendar class.

//Obtain year, month and day information
public void getDetailDate(){
    LocalDate today = LocalDate.now();
    int year = today.getYear();
    int month = today.getMonthValue();
    int day = today.getDayOfMonth();

    System.out.printf("Year : %d  Month : %d  day : %d t %n", year, month, day);
}

3. Process specific dates

In the first example, we created the date of the day very easily through the static factory method now().

We can also call another useful factory method, LocalDate Of() creates any date. This method needs to pass in year, month and day as parameters and return the corresponding LocalDate instance. The advantage of this method is that it doesn't make the design mistakes of the old API again. For example, the year starts in 1900, the month starts from 0, and so on. Date WYSIWYG, as the following example shows January 21, which is straightforward.

//Process specific dates
public void handleSpecilDate(){
    LocalDate dateOfBirth = LocalDate.of(2018, 01, 21);
    System.out.println("The specil date is : " + dateOfBirth);
}

4. Judge whether the two dates are equal

In real life, one kind of time processing is to judge whether two dates are equal. There are always such problems in project development.
The following example will help you solve it in Java 8. LocalDate overloads the equal method.

Note that if the compared date is of character type, it needs to be parsed into a date object before judgment.

Take the following example:

//Judge whether the two dates are equal
public void compareDate(){
    LocalDate today = LocalDate.now();
    LocalDate date1 = LocalDate.of(2018, 01, 21);

    if(date1.equals(today)){
           System.out.printf("TODAY %s and DATE1 %s are same date %n", today, date1);
    }
}

5. Check for recurring events like birthdays

Another date and time processing in Java is to check periodic events such as birthdays, anniversaries, legal holidays (National Day and Spring Festival), or sending emails to customers at a fixed time every month.

How do you check these festivals or other periodic events in Java? The answer is the MonthDay class. This class combines months and days, excluding years, which means you can use it to judge events that occur every year. Java reply to the interview question in the official account, and send you an interview question.

Similar to this class, there is also a YearMonth class. These classes are also immutable and thread safe value types. Let's check the periodic events through MonthDay:

//Date of processing periodicity
public void cycleDate(){
    LocalDate today = LocalDate.now();
    LocalDate dateOfBirth = LocalDate.of(2018, 01, 21);

    MonthDay birthday = MonthDay.of(dateOfBirth.getMonth(), dateOfBirth.getDayOfMonth());
    MonthDay currentMonthDay = MonthDay.from(today);

    if(currentMonthDay.equals(birthday)){
       System.out.println("Many Many happy returns of the day !!");
    }else{
       System.out.println("Sorry, today is not your birthday");
    }
}

6. Get the current time

Much like the example of getting a date, getting a time uses the LocalTime class, a close relative of LocalDate with only time and no date. You can call the static factory method now() to get the current time. The default format is hh:mm:ss:nnn.

//Get current time
public void getCurrentTime(){
    LocalTime time = LocalTime.now();
    System.out.println("local time now : " + time);
}

7. Add hours to the existing time

Java 8 provides a better plusHours() method to replace add() and is compatible. Note that these methods return a brand-new LocalTime instance. Because of its immutability, you must assign a value to the variable after returning.

//Increase hours
public void plusHours(){
    LocalTime time = LocalTime.now();
    LocalTime newTime = time.plusHours(2); //Add two hours
    System.out.println("Time after 2 hours : " +  newTime);
}

8. How to calculate the date after one week

Similar to the previous example, which calculates the time after two hours, this example calculates the date after one week. The LocalDate date does not contain time information. Its plus() method is used to add days, weeks and months. The chrononunit class declares these time units. Since LocalDate is also an invariant type, it must be assigned with a variable after returning.

You can add a month, a year, an hour, a minute or even a century in the same way. For more options, you can view the chrononunit class in the Java 8 API.

//How to calculate the date after one week
public void nextWeek(){
    LocalDate today = LocalDate.now();
    LocalDate nextWeek = today.plus(1, ChronoUnit.WEEKS);    //Use variable assignment
    System.out.println("Today is : " + today);
    System.out.println("Date after 1 week : " + nextWeek);
}

9. Calculate the date before or after one year

Next, in the above example, we increase the number of days, weeks or months through the plus() method of LocalDate. In this example, we use the minus() method to calculate the date one year ago.

//Calculate the date one year ago or one year later
public void minusDate(){
    LocalDate today = LocalDate.now();
    LocalDate previousYear = today.minus(1, ChronoUnit.YEARS);
    System.out.println("Date before 1 year : " + previousYear);

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

10. Use the Clock class of Java 8

Java 8 adds a Clock class to obtain the time stamp at that time or the date and time information in the current time zone. Previously used system Currenttimeinmillis() and timezone All places of getdefault () can be replaced by Clock.

public void clock(){
    //Return the current time according to the system time and set it to UTC.
    Clock clock = Clock.systemUTC();
    System.out.println("Clock : " + clock);

    //Return time according to the system clock area
    Clock defaultClock = Clock.systemDefaultZone();
    System.out.println("Clock : " + clock);
}

11. Judge whether the date is earlier or later than another date

The LocalDate class has two methods, isBefore() and isAfter(), for comparing dates. When the isBefore() method is called, it returns true if the given date is less than the current date.

//How to use Java to determine whether a date is earlier or later than another date
public void isBeforeOrIsAfter(){
    LocalDate today = LocalDate.now(); 

    LocalDate tomorrow = LocalDate.of(2018, 1, 29);
    if(tomorrow.isAfter(today)){
        System.out.println("Tomorrow comes after today");
    }

    //Minus one day
    LocalDate yesterday = today.minus(1, ChronoUnit.DAYS);

    if(yesterday.isBefore(today)){
        System.out.println("Yesterday is day before today");
    }
}

12. Processing time zone

Java 8 not only separates the date and time, but also separates the time zone. Now there are a series of separate classes, such as ZoneId, to handle a specific time zone, and ZoneDateTime class to represent the time in a time zone.

//Gets the time below a specific time zone
public void getZoneTime(){
    //Set time zone
    ZoneId america = ZoneId.of("America/New_York");

    LocalDateTime localtDateAndTime = LocalDateTime.now();

    ZonedDateTime dateAndTimeInNewYork  = ZonedDateTime.of(localtDateAndTime, america );
    System.out.println("The current date and time are in a specific time zone : " + dateAndTimeInNewYork);
}

13. How to reflect the fixed date

For example, it indicates a fixed date such as the expiration of a credit card. Similar to the example of MonthDay checking for duplicate events, YearMonth is another composite class, which is used to represent credit card expiration date, FD expiration date, futures option expiration date, etc.

You can also use this class to get the total number of days in the current month. The lengthOfMonth() method of the YearMonth instance can return the number of days in the current month, which is very useful in judging whether February has 28 days or 29 days.

//Use the # YearMonth class to handle specific dates
public void checkCardExpiry(){
    YearMonth currentYearMonth = YearMonth.now();
    System.out.printf("Days in month year %s: %d%n", currentYearMonth, currentYearMonth.lengthOfMonth());

    YearMonth creditCardExpiry = YearMonth.of(2028, Month.FEBRUARY);
    System.out.printf("Your credit card expires on %s %n", creditCardExpiry);
}

14. Check leap years

The LocalDate class has a very practical method isLeapYear() to judge whether the instance is a leap year. If you still want to reinvent the wheel, here is a code example, a program written in pure Java logic to judge leap years.

//Check leap year
public void isLeapYear(){
    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");
    }
}

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 Java time. Period class to do calculations. In the following example, we calculate the number of months between the current day and a future day.

The following example: it's January now. It's three months away from May

//Calculate the number of days and months between two dates
public void calcDateDays(){
    LocalDate today = LocalDate.now();

    LocalDate java8Release = LocalDate.of(2018, Month.MAY, 14);

    Period periodToNextJavaRelease = Period.between(today, java8Release);

    System.out.println("Months left between today and Java 8 release : "
                                           + periodToNextJavaRelease.getMonths() );
}

16. Date and time including time difference information

ZoneOffset class is used to represent the time zone. For example, the difference between India and GMT or UTC standard time zone is + 05:30. You can use ZoneOffset Of() static method to get the corresponding time zone. Once the time difference is obtained, you can create an OffSetDateTime object by passing in LocalDateTime and ZoneOffset.

public void ZoneOffset(){
    LocalDateTime datetime = LocalDateTime.of(2018, Month.FEBRUARY, 14, 19, 30);
    ZoneOffset offset = ZoneOffset.of("+05:30");
    OffsetDateTime date = OffsetDateTime.of(datetime, offset);  
    System.out.println("Date and Time with timezone offset in Java : " + date);
}

17. Get the current timestamp

The Instant class has a static factory method. now() will return the current timestamp, as shown below:

public void getTimestamp(){
    Instant timestamp = Instant.now();
    System.out.println("What is value of this instant " + timestamp);
}

18. Use predefined formatting tools to parse or format dates

Java 8 introduces a new date and time format tool, which is thread safe and easy to use. It comes with some commonly used built-in formatting tools.

The following example uses basic\_ ISO\_ The date formatting tool formats February 10, 2018 as 20180210.

//Use predefined formatting tools to parse or format dates
public void formateDate(){
    String dayAfterTommorrow = "20180210";
    LocalDate formatted = LocalDate.parse(dayAfterTommorrow, DateTimeFormatter.BASIC_ISO_DATE);
    System.out.printf("Date generated from String %s is %s %n", dayAfterTommorrow, formatted);
}

last

Finally, attach all codes

package com.wq.study.java8.date;

import java.time.Clock;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.MonthDay;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.Period;
import java.time.YearMonth;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Date;

public class DateTest {

    //Get today's date
    public void getCurrentDate(){
        LocalDate today = LocalDate.now();
        System.out.println("Today's Local date : " + today);

        //This is for comparison
        Date date = new Date();
        System.out.println(date);
    }

    //Obtain year, month and day information
    public void getDetailDate(){
        LocalDate today = LocalDate.now();
        int year = today.getYear();
        int month = today.getMonthValue();
        int day = today.getDayOfMonth();

        System.out.printf("Year : %d  Month : %d  day : %d t %n", year, month, day);
    }

    //Process specific dates
    public void handleSpecilDate(){
        LocalDate dateOfBirth = LocalDate.of(2018, 01, 21);
        System.out.println("The specil date is : " + dateOfBirth);
    }

    //Judge whether the two dates are equal
    public void compareDate(){
        LocalDate today = LocalDate.now();
        LocalDate date1 = LocalDate.of(2018, 01, 21);

        if(date1.equals(today)){
            System.out.printf("TODAY %s and DATE1 %s are same date %n", today, date1);
        }
    }

    //Date of processing periodicity
    public void cycleDate(){
        LocalDate today = LocalDate.now();
        LocalDate dateOfBirth = LocalDate.of(2018, 01, 21);

        MonthDay birthday = MonthDay.of(dateOfBirth.getMonth(), dateOfBirth.getDayOfMonth());
        MonthDay currentMonthDay = MonthDay.from(today);

        if(currentMonthDay.equals(birthday)){
           System.out.println("Many Many happy returns of the day !!");
        }else{
           System.out.println("Sorry, today is not your birthday");
        }
    }

    //Get current time
    public void getCurrentTime(){
        LocalTime time = LocalTime.now();
        System.out.println("local time now : " + time);
    }

    //Increase hours
    public void plusHours(){
        LocalTime time = LocalTime.now();
        LocalTime newTime = time.plusHours(2); //Add two hours
        System.out.println("Time after 2 hours : " +  newTime);
    }

    //How to calculate the date after one week
    public void nextWeek(){
        LocalDate today = LocalDate.now();
        LocalDate nextWeek = today.plus(1, ChronoUnit.WEEKS);
        System.out.println("Today is : " + today);
        System.out.println("Date after 1 week : " + nextWeek);
    }

    //Calculate the date one year ago or one year later
    public void minusDate(){
        LocalDate today = LocalDate.now();
        LocalDate previousYear = today.minus(1, ChronoUnit.YEARS);
        System.out.println("Date before 1 year : " + previousYear);

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

    public void clock(){
        //Return the current time according to the system time and set it to UTC.
        Clock clock = Clock.systemUTC();
        System.out.println("Clock : " + clock);

        //Return time according to the system clock area
        Clock defaultClock = Clock.systemDefaultZone();
        System.out.println("Clock : " + clock);
    }

    //How to use Java to determine whether a date is earlier or later than another date
    public void isBeforeOrIsAfter(){
        LocalDate today = LocalDate.now(); 

        LocalDate tomorrow = LocalDate.of(2018, 1, 29);
        if(tomorrow.isAfter(today)){
            System.out.println("Tomorrow comes after today");
        }

        LocalDate yesterday = today.minus(1, ChronoUnit.DAYS);

        if(yesterday.isBefore(today)){
            System.out.println("Yesterday is day before today");
        }
    }

    //Time zone processing
    public void getZoneTime(){
        //Set time zone
        ZoneId america = ZoneId.of("America/New_York");

        LocalDateTime localtDateAndTime = LocalDateTime.now();

        ZonedDateTime dateAndTimeInNewYork  = ZonedDateTime.of(localtDateAndTime, america );
        System.out.println("The current date and time are in a specific time zone : " + dateAndTimeInNewYork);
    }

    //Use the # YearMonth class to handle specific dates
    public void checkCardExpiry(){
        YearMonth currentYearMonth = YearMonth.now();
        System.out.printf("Days in month year %s: %d%n", currentYearMonth, currentYearMonth.lengthOfMonth());

        YearMonth creditCardExpiry = YearMonth.of(2028, Month.FEBRUARY);
        System.out.printf("Your credit card expires on %s %n", creditCardExpiry);
    }

    //Check leap year
    public void isLeapYear(){
        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");
        }
    }

    //Calculate the number of days and months between two dates
    public void calcDateDays(){
        LocalDate today = LocalDate.now();

        LocalDate java8Release = LocalDate.of(2018, Month.MAY, 14);

        Period periodToNextJavaRelease = Period.between(today, java8Release);

        System.out.println("Months left between today and Java 8 release : "
                                           + periodToNextJavaRelease.getMonths() );
    }

    //Date and time with time difference information
    public void ZoneOffset(){
        LocalDateTime datetime = LocalDateTime.of(2018, Month.FEBRUARY, 14, 19, 30);
        ZoneOffset offset = ZoneOffset.of("+05:30");
        OffsetDateTime date = OffsetDateTime.of(datetime, offset);  
        System.out.println("Date and Time with timezone offset in Java : " + date);
    }

    //Get timestamp
    public void getTimestamp(){
        Instant timestamp = Instant.now();
        System.out.println("What is value of this instant " + timestamp);
    }

    //Use predefined formatting tools to parse or format dates
    public void formateDate(){
        String dayAfterTommorrow = "20180210";
        LocalDate formatted = LocalDate.parse(dayAfterTommorrow, DateTimeFormatter.BASIC_ISO_DATE);
        System.out.printf("Date generated from String %s is %s %n", dayAfterTommorrow, formatted);
    }

    public static void main(String[] args) {
        DateTest dt = new DateTest();

        dt.formateDate();
    }

}

summary

Key points of Java 8 date time API

  • Provides javax time. Zoneid gets the time zone.
  • LocalDate and LocalTime classes are provided.
  • All date and time APIs of Java 8 are immutable classes and thread safe, while Java. Com in the existing date and calendar APIs util. Date and SimpleDateFormat are non thread safe.
  • The main package is Java Time, including some classes representing date, time and time interval. There are two sub packages Java time. Format is used for formatting, Java time. Temporary is used for lower level operations.
  • The time zone represents the standard time commonly used in an area of the earth. Each time zone has a code. The format is usually composed of region / city (Asia/Tokyo), plus the time difference from Greenwich or UTC. For example, the time difference in Tokyo is + 09:00.

Keywords: Java

Added by webwalker00 on Mon, 21 Feb 2022 03:43:09 +0200