Check two Calendar Instance Has Same Time Instance In Java


On many occasions we need to check if two calendar objects or Date are on the time instance. This cane be achieved by comparing the long millisecond time of the two objects. Here is example to do this.

    public static boolean isSameInstant(Calendar cal1, Calendar cal2) {
        if (cal1 == null || cal2 == null) {
            throw new IllegalArgumentException("The date must not be null");
        }
        return cal1.getTime().getTime() == cal2.getTime().getTime();
    }

    public static boolean isSameInstant(Date date1, Date date2) {
        if (date1 == null || date2 == null) {
            throw new IllegalArgumentException("The date must not be null");
        }
        return date1.getTime() == date2.getTime();
    }

    public static boolean isSameInstant(Date date1, Calendar cal1) {
        if (date1 == null || cal1 == null) {
            throw new IllegalArgumentException("The date must not be null");
        }
        return date1.getTime() == cal1.getTime().getTime();
    }

In above code we are calling cal1.getTime().getTime() metho to get time in long in case of Calendar instance and date1.getTime() in case of Date instance.

Or you can use commons-lang apache lib’s DateUtils class isSameInstant method.

Maven dependency for apache commons-lang lib

<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.6</version>
</dependency>