New features of JDK1.8 date

1, JDK8 upgrades the date class and adds the increase or decrease method of the date

 private static void JDK8Datetest() {
        //Defines the date and time of a string
        String s = "2020 00 Nov 11:00:00";
        //Static methods return formatted objects
        DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy year MM month dd day HH:mm:ss");
        //Pass in the string time and format
        LocalDateTime parse = LocalDateTime.parse(s, pattern);
        //Advance one day based on the current date to get a new date
        LocalDateTime localDateTime = parse.plusDays(1);
        //Format the new date into a string
        String date = localDateTime.format(pattern);
        //Output printing
        System.out.println(date);//The output result information is: 00:00:00, November 12, 2020 
}

2, JDK8 get time object

         /**
         * Before JDK8, we mainly used three classes to process date and time,
         * Date
         * SimpleDateFormat
         * Calendar(Wait for a brief introduction later).
         * There are more or less problems in the use of these three classes. For example, SimpleDateFormat is not thread safe,
         * For example, the months obtained by Date and Calendar are 0 to 11, rather than 1 to 12 in real life,*/
        Date date1 = new Date();
        System.out.println(date1.getMonth());// The printing result of month information obtained before jdk1.8: 9 the actual month of the system is 10

        //1.jdk8 get the current system time
        LocalDateTime now = LocalDateTime.now();
        System.out.println(now);//2021-10-11T20:12:55.351

        //2.jdk8 get the specified time
        LocalDateTime time = LocalDateTime.of(2021, 11, 11, 11, 11, 11);
        System.out.println(time);//2021-11-11T11:11:11
        /**
         * Explanation:
         * 1.now():The time obtained is the time of the current system
         * 2.of():Method parameters can specify the time
         * */

3, JDK8 gets each value in time

        /**
         * JDK8 Gets each value in the time
         * LocalDateTime Common methods:
         * getYear():Get year minute in time
         * getMoth():Gets the month in the time
         * getMothValue():Get the month from January to December
         * getDayOfYear():Get day 1-31
         * getDateOfYear()Get the day of the year
         * getDayOfWeek():Gets the English representation of the week. Gets the enumeration value
         * getMinute():Hu Oh, go for a minute
         * getHour():Get hours
         * */
        LocalDateTime now1 = LocalDateTime.now();
        //Get year
        int year = now1.getYear();
        System.out.println(year);
        //Get the month in English means to get the enumeration value
        Month month = now1.getMonth();
        System.out.println(month);

        //Get month 1-12
        int monthValue = now1.getMonthValue();
        System.out.println(monthValue);

        //Get the day of the month 1-31
        int dayOfMonth = now1.getDayOfMonth();
        System.out.println(dayOfMonth);

        //Get the day of the year 1-366
        int dayOfYear = now1.getDayOfYear();
        System.out.println(dayOfYear);

        // Gets the English representation of the week. Gets the enumeration value
        DayOfWeek dayOfWeek = now1.getDayOfWeek();
        System.out.println(dayOfWeek);

        //Get minutes
        int minute = now1.getMinute();
        System.out.println(minute);

        //Get hours
        int hour = now1.getHour();
        System.out.println(hour);

4, JDK8 time conversion --- only get month, day, hour, minute and second

         /**
         * JDK8 Time class -- conversion method
         * now():Get current system time
         * toLocalDate():Show only the date of time
         *toLocalTime():Time of war
         * */
        LocalDateTime now2 = LocalDateTime.now();//Get current system time
        //To convert to localDate object, you only need to display the year, month and day information
        LocalDate localDate = now2.toLocalDate();
        System.out.println(localDate);//2021-10-11
        //Convert to localTime object, showing only hours, minutes and seconds
        LocalTime localTime = now2.toLocalTime();
        System.out.println(localTime);//20:56:14.835

5, JDK8 time class formatting and parsing

       /**
         * JDK8 Time class - formatting and parsing
         * */
        //Get current system time
        LocalDateTime now3 = LocalDateTime.now();
        System.out.println(now3);//2021-10-11T21:00:25.758
        System.out.println("==============================");
        //Formatting requires a formatted Date object datetomefromatter (format)
        String format = now.format(DateTimeFormatter.ofPattern("yyyy year MM month dd day HH:mm:ss"));
        System.out.println(format);//October 11, 2021 21:02:40
        System.out.println("==============================");
        //Resolution: String s = "November 11, 2020 0:0:0"// Must be in the same format as specified for resolution
        String s1 = "2021 00 Nov 11:00:00";
        //Pass in the date string that needs to be parsed
        LocalDateTime parse1 = LocalDateTime.parse(s1, DateTimeFormatter.ofPattern("yyyy year MM month dd day HH:mm:ss"));
        System.out.println(parse1);//2021-11-11T00:00
        System.out.println("==============================");

6, JDK8 time class - Method of plus series

    //Get current system time
    LocalDateTime now = LocalDateTime.now();
    //Year + 1
    LocalDateTime year = now.plusYears(1); //A positive number or a negative number 0 will do
    System.out.println(year.getYear());
    //Month + 1
    LocalDateTime month = now.plusMonths(1);
    System.out.println(month.getMonthValue());
    //There are days, hours, minutes, seconds and weeks. The usage of this method is the same

7, JDK8 time class - Method of minus series

   //Reverse thinking  
	The parameter is a positive time push forward (It refers to the past time)  
    The parameter is a negative time push back (It refers to the time in the future)
   
    LocalDateTime now = LocalDateTime.now();
 	//Passing a positive number is subtracting one year from now, passing - 1 is adding one year to now, and 0 has no meaning
    //The new time object LocalDateTime is obtained
	LocalDateTime years = now.minusYears(0);
    System.out.println(years.getYear());

    //Passing a positive number is in the month of now - 1
    LocalDateTime month = now.minusMonths(1);
    System.out.println(month.getMonthValue());
    //The daily hours, minutes, seconds and weeks are consistent

8, JDK8 time class - Method of with series

    Direct modification time,What you get is a new time object LocalDateTime
    LocalDateTime now = LocalDateTime.now();
    //Set the number of years to be passed in. If a negative number is passed in, no error will be reported
    LocalDateTime year = now.withYear(1);
    System.out.println(year);
    //Set the value passed in by month, but in January December
    LocalDateTime month = now.withMonth(12);
    System.out.println(month.getMonthValue());

    //Set the day of the month
    LocalDateTime day = now.withDayOfMonth(15);
    System.out.println(day);

    //Displays the day ordinal of the year. The display format is the month ordinal of the year
    LocalDateTime dayOfYear = now.withDayOfYear(112);
    System.out.println(dayOfYear);	

9, JDK8 time class - time interval object

        LocalDate date1 = LocalDate.of(2020, 12, 21);
        LocalDate date2 = LocalDate.of(2022, 11, 25);
        Period between1 = Period.between(date1, date2);
        System.out.println(between1);
		//P1Y11M4D  
		//P time interval object 1Y represents a year 11M represents 11 months 4D represents 4 days
		// Year when this period is obtained
        int years = between1.getYears();
        System.out.println(years);
		//Get the month when this period
        int months = between1.getMonths();
        System.out.println(months);
		//Gets the number of days during this period
        int days = between1.getDays();
        System.out.println(days);
		//Indicates the total number of months between the two time periods
        long l = between1.toTotalMonths();
        System.out.println(l);


    LocalDateTime date1 = LocalDateTime.of(2020, 12, 21, 11, 11, 11);
    LocalDateTime date2 = LocalDateTime.of(2020, 12, 21, 12, 12, 12);
    Duration duration = Duration.between(date1, date2);
    System.out.println(duration);
	//PT1H1M1S PT interval object 1H interval 1 hour 1M interval 1 minute 1S interval 1 second

    long l = duration.toSeconds();
    System.out.println(l);//3661 seconds between
    long l1 = duration.toMillis();
    System.out.println(l1);//3661000 milliseconds of interval
    long l2 = duration.toNanos();
    System.out.println(l2);//3661000000000 / / nanoseconds of interval

10, JDK8 time class - Summary

JDK1.8 pre date function API

1 java.lang.System class
    public static native long currentTimeMillis();
    Used to return the time difference in milliseconds between the current time and 0:0:0 on January 1, 1970
   
2 java.util.Date class
    Two constructors
    new Date(); —> current time
    new Date(Long milliseconds) - > creates a specified date based on the number of milliseconds

    Use of two methods
    toString() displays the current year, month, day, hour, minute and second
    getTime() gets the corresponding number of milliseconds (timestamp) of the current date object

3 java.text.SimpleDateFormat class
     The API of Date class is not easy to internationalize, and most of them are abandoned,
    The SimpleDateFormat class is a concrete class that formats and parses time in a locale dependent manner
    The format(Date d) method formats the time in a specific format
    parse(String s)   Method parses a string into time
    
4. Java.util.calendar Calendar Class
    Get an instance of Calendar
    An object that uses its subclass (GregorianCalendar)
    Get the Calendar instance using Calendar.getInstance()
    common method
    1,set()
    calendar.set(Calendar.DAY_OF_MONTH,22) - > set the date to the day of the month
    
    2,get()
    Calendar. Get (calendar. Day_of_month) ---- > the day of the month. The return value is int
    calendar.get(Calendar.DAY_OF_YEAR) - > the day of the year
   
    3,add()
    Calendar. Add (calendar. Day_of_month, 3) - -- > add 3 days to the existing date
    
    4,getTime()
    calendar.getTime(); —> Return Date()
    
    5,setTime()
    calendar.setTime(new Date()) - > set the date to a certain date     

JDK1.8 post date function API

Variability: classes such as date and time should be immutable, ---- > return a value, and the original object remains unchanged
Offset: the year in Date starts from 1900 and the month starts from 0
The date represents September 8, 2020 by subtracting new Date(2020-1900,9-1,8)
format; Formatting dates is only useful for Date, not Calendar
Thread is unsafe and cannot handle leap seconds, etc
Java8 absorbed the essence of Joda-Time(java date processing time library), opened the new API, and the new java.time contained the following classes.
    Local datelocaldate
    Local timelocaltime
    Local datetime
    Time zone ZonedDateTime
    Durationjoda time
    
1. API for new date of jdk8
    java.time - base package containing value objects
    java.time.chrono - provides access to different calendar systems
    java.time.format - format and parse time and date
    Java.time.temporary - contains the underlying framework and extension features
    java.time.zone - contains classes that support time zones     

2 LocalDate,LocalTime,LocalDateTime
    Get current time
   LocalDate localDate = LocalDate.now();   // Mm / DD / yy`
   LocalTime localTime = LocalTime.now();   // Day minute second
   LocalDateTime localDateTime = LocalDateTime.now();

   // LocalDateTime   High frequency of use
   // of() sets the specified month, day, hour, minute and second   Reflect non offset
   LocalDateTime dateTime = LocalDateTime.of(2019, 04, 10, 23, 03);
   // plus Series   Addition and subtraction of time
   // Addition and subtraction of minus series time
   // wiht series   Set time

3 Instant   time stamp   Millisecond value between 00:00:00 on January 1, 1970 and a certain time
   An instantaneous point on the timeline, which may be used to record the event timestamp of the application
   The accuracy of Instant can reach nanosecond level    
    // Instant is very similar to java.util.Date

    // Get the standard time of the prime meridian
    Instant now = Instant.now();
    System.out.println(now);    

    // Time of East eighth District        Offset
    OffsetDateTime offsetDateTime =now.atOffset(ZoneOffset.ofHours(8));
    System.out.println(offsetDateTime);

    // Milliseconds since January 1, 1970, 0:0:0(UTC)
    long l = now.toEpochMilli();
    System.out.println(l);

4. Java.time.format.datetimeformatter formats or parses time
   Custom format
   Datetimeformatter pattern = datetimeformatter. Ofpattern() ("yyyy MM DD HH: mm: SS") -- > is similar to SimpleDateFormat     
   
5 Duration: Duration, used to calculate the interval between two "times"
  Date interval: Period, used to calculate the interval between two dates  

Application scenario

1. The LocalDate class uses an isLeapYear() method to return whether the year corresponding to the current LocalDate is a leap year     
   boolean leapYear = LocalDate.now().isLeapYear();

2 how to judge whether a date is before or after another date in java,
  How to determine whether a date is before or after another date or equal,
  In Java 8, isBefore() is used in the LocalDate class
  isAfter() and equals() methods to compare the two dates.
  If the date on which the method is called is earlier than the given date, the isBefore() method returns true

3 check whether the two dates are equal in Java 8
  LocalDate overrides the equals method to compare dates

4 how to check repeated events, such as birthday, in Java 8
  Another task related to time and date in java is to check for duplicate events, such as monthly bill day
  How to judge whether it is a festival or repeated event in java, use the MonthDay class. This class is composed of month and day. It is not allowed    Including year information,
  It can be used to represent some dates or other combinations that occur repeatedly every year. Like other classes in the new date library, it is also non editable    It is thread safe, and it is also a value class.

How to represent a fixed date, such as the expiration time of a credit card
  Just as MonthDay represents a recurring day, YearMonth is another combination, which represents something like credit    Card repayment date, time deposit maturity date,
  options expiration date. You can use this class to find out how many days there are in this month,
  The LengthOfMonth() method returns the number of days of the YearMonth instance, which is useful for checking whether February is 2      Month is very useful

Tags: Java

Posted on Mon, 11 Oct 2021 15:13:46 -0400 by adamddickinson