How to compare dates in Java?
In Java, you can use the compareTo() method to compare the sizes of two dates.
import java.time.LocalDate;
public class CompareDates {
public static void main(String[] args) {
LocalDate date1 = LocalDate.of(2021, 1, 1);
LocalDate date2 = LocalDate.of(2022, 1, 1);
int result = date1.compareTo(date2);
if(result < 0){
System.out.println("date1 在 date2 之前");
}else if(result > 0){
System.out.println("date1 在 date2 之后");
}else{
System.out.println("两个日期相等");
}
}
}
In the example above, we created two LocalDate objects, date1 and date2, to represent January 1st, 2021 and January 1st, 2022, respectively. We then used the compareTo() method to compare these two dates and output relevant information based on the result of the comparison.
If the compareTo() method returns a value less than 0, it means date1 is before date2; if it returns a value greater than 0, it means date1 is after date2; if it returns a value equal to 0, it means the two dates are equal.