Java language implements comparison of two Date dates

In Java, you can use the method or method Dateof the class to compare the order of dates of two types.compareTo()before()after()Date

  1. How to use compareTo():

    Date date1 = ...; // 第一个日期
    Date date2 = ...; // 第二个日期
    
    int result = date1.compareTo(date2);
    if (result < 0) {
          
          
        // date1 在 date2 之前
    } else if (result > 0) {
          
          
        // date1 在 date2 之后
    } else {
          
          
        // date1 和 date2 相等
    }
    

    compareTo()The method returns an integer value, which is a negative number if the first date is before the second date, a positive number if the first date is after the second date, or 0 if the two dates are equal.

  2. Use before()and after()methods:

    Date date1 = ...; // 第一个日期
    Date date2 = ...; // 第二个日期
    
    if (date1.before(date2)) {
          
          
        // date1 在 date2 之前
    } else if (date1.after(date2)) {
          
          
        // date1 在 date2 之后
    } else {
          
          
        // date1 和 date2 相等
    }
    

    before()The method returns a Boolean value if the date on which the method is called is before the parameter date, otherwise it is truereturned false. after()The method, on the contrary, returns if the date on which the method is called is after the parameter date, trueotherwise it returns false.

Please note that Java 8 introduces new date and time APIs ( java.timepackages), and it is recommended to use classes such as LocalDate, etc. to handle dates and times. LocalDateTimeIn the new API, you can use compareTo()the, isBefore(), and isAfter()methods to compare the order of dates.

LocalDate date1 = ...; // 第一个日期
LocalDate date2 = ...; // 第二个日期

int result = date1.compareTo(date2);
if (result < 0) {
    
    
    // date1 在 date2 之前
} else if (result > 0) {
    
    
    // date1 在 date2 之后
} else {
    
    
    // date1 和 date2 相等
}

Hope this helps!

Guess you like

Origin blog.csdn.net/qq_44543774/article/details/133208532