Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

So sánh Date trong Java

Để so sánh ngày tháng trong Java, dùng phương thức compareTo(). Cú pháp:

public int compareTo(Date anotherDate)

Ở đây, anotherDate là ngày cần so sánh. Giá trị trả về: 0 nếu argument Date bằng Date này; nhỏ hơn 0 nếu Date này trước Date argument; lớn hơn 0 nếu Date này sau Date argument.

Ví dụ 1: compareTo()

import java.util.*;

public class Demo {
    public static void main(String[] args) {
        // Tạo hai date (Note: constructor Date(int year, int month, int date) đã deprecated)
        Date date = new Date(19, 3, 25);  // 1919-04-25 (year 1919 = 1900+19)
        Date date2 = new Date(19, 9, 12); // 1919-10-12
        
        int comparison = date.compareTo(date2);
        int comparison2 = date2.compareTo(date);
        int comparison3 = date.compareTo(date);
        
        System.out.println("Comparison Result: " + comparison);   // -1
        System.out.println("Comparison2 Result: " + comparison2); // 1
        System.out.println("Comparison3 Result: " + comparison3); // 0
    }
}

Kết quả

Comparison Result: -1
Comparison2 Result: 1
Comparison3 Result: 0

Ví dụ 2: equals() - So sánh bằng nhau dựa trên milliseconds

import java.util.*;

public class Demo {
    public static void main(String[] args) {
        Date date = new Date(70, 1, 10);  // 1970-02-10
        Date date2 = new Date(70, 1, 10);
        boolean check = date.equals(date2);
        System.out.println("Dates are equal: " + check);
    }
}

Kết quả

Dates are equal: true

Khuyến nghị hiện đại: Từ Java 8, nên dùng java.time.LocalDate, LocalDateTime, Instant thay cho java.util.Date. Các class mới có phương thức isBefore(), isAfter(), isEqual(), compareTo() rõ ràng hơn và immutable.