javadatetimejava.util.calendar

calendar.getTime().equals(cal1) return false though both calendars has same time


    Calendar calendar = Calendar.getInstance();
    Calendar cal1 = Calendar.getInstance();

    if (calendar.getTime().equals(cal1.getTime())) {
        System.out.println("Hi!");
    }

Printing calendar.getTime() and cal1.getTime() returns

Mon Aug 10 16:00:10 IST 2020
Mon Aug 10 16:00:11 IST 2020

Following code works as expected printing Hi! it should be return true for equals check but it doesn't.

    if (!calendar.getTime().after(cal1.getTime()) || !calendar.getTime().before(cal1.getTime())) {
        System.out.println("Hi!");
    }

Then why it is returning false for equals check?


Solution

  • Mon Aug 10 16:00:10 IST 2020 and Mon Aug 10 16:00:11 IST 2020 differ in seconds.

    Also, I suggest you do not use the outdated and error-prone java.util date-time API. Use the modern date time API instead as shown below:

    import java.time.LocalDateTime;
    import java.time.format.DateTimeFormatter;
    import java.util.Locale;
    
    public class Main {
        public static void main(String[] args) {
            String dateTimeStr1 = "Mon Aug 10 16:00:10 IST 2020";
            String dateTimeStr2 = "Mon Aug 10 16:00:11 IST 2020";
    
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("E MMM dd HH:mm:ss z u", Locale.ENGLISH);
    
            LocalDateTime date1 = LocalDateTime.parse(dateTimeStr1, formatter);
            LocalDateTime date2 = LocalDateTime.parse(dateTimeStr2, formatter);
    
            System.out.println(date1.equals(date2));
        }
    }
    

    Output:

    false
    

    How to compare them by excluding seconds:

    import java.time.LocalDateTime;
    import java.time.LocalTime;
    import java.time.format.DateTimeFormatter;
    import java.util.Locale;
    
    public class Main {
        public static void main(String[] args) {
            String dateTimeStr1 = "Mon Aug 10 16:00:10 IST 2020";
            String dateTimeStr2 = "Mon Aug 10 16:00:11 IST 2020";
    
            // Define the formatter
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("E MMM dd HH:mm:ss z u", Locale.ENGLISH);
    
            // Parse the date-time strings into LocalDateTime
            LocalDateTime date1 = LocalDateTime.parse(dateTimeStr1, formatter);
            LocalDateTime date2 = LocalDateTime.parse(dateTimeStr2, formatter);
    
            // Create LocalDateTime instances from the parsed ones by excluding seconds
            LocalDateTime date1WithoutSec = LocalDateTime.of(date1.toLocalDate(),
                    LocalTime.of(date1.getHour(), date1.getMinute()));
            LocalDateTime date2WithoutSec = LocalDateTime.of(date2.toLocalDate(),
                    LocalTime.of(date2.getHour(), date2.getMinute()));
    
            System.out.println(date1WithoutSec.equals(date2WithoutSec));
        }
    }
    

    Output:

    true