Computer >> Máy Tính >  >> Lập trình >> Java

Làm thế nào để so sánh hai ngày trong Java?


Trong Java, hai ngày có thể được so sánh bằng cách sử dụng CompareTo () phương pháp Có thể so sánh giao diện. Phương thức này trả về '0' nếu cả hai ngày đều bằng nhau , nó trả về giá trị " lớn hơn 0" nếu date1 là sau date2 và nó trả về giá trị "nhỏ hơn 0" nếu date1 trước date2.

Cú pháp

int compareTo(T o)

Ví dụ

import java.text.*;
import java.util.Date;
public class CompareTwoDatesTest {
   public static void main(String[] args) throws ParseException {
      SimpleDateFormat sdformat = new SimpleDateFormat("yyyy-MM-dd");
      Date d1 = sdformat.parse("2019-04-15");
      Date d2 = sdformat.parse("2019-08-10");
      System.out.println("The date 1 is: " + sdformat.format(d1));
      System.out.println("The date 2 is: " + sdformat.format(d2));
      if(d1.compareTo(d2) > 0) {
         System.out.println("Date 1 occurs after Date 2");
      } else if(d1.compareTo(d2) < 0) {
         System.out.println("Date 1 occurs before Date 2");
      } else if(d1.compareTo(d2) == 0) {
         System.out.println("Both dates are equal");
      }
   }
}

Trong ví dụ trên, ngày d1 xảy ra trước ngày d2, vì vậy nó có thể hiển thị " Ngày 1 xảy ra trước Ngày 2 "trong bảng điều khiển.

Đầu ra

The date 1 is: 2019-04-15
The date 2 is: 2019-08-10
Date 1 occurs before Date 2