Comparing two Calendar objects

前端 未结 6 984
死守一世寂寞
死守一世寂寞 2020-12-16 10:21

I want to compare two Calendar objects to see if they both contain the same date. I don\'t care about any value below days.

I\'ve implemented this and I can\'t think

6条回答
  •  孤城傲影
    2020-12-16 10:28

    You can use somehing like DateUtils

    public boolean isSameDay(Calendar cal1, Calendar cal2) {
        if (cal1 == null || cal2 == null)
            return false;
        return (cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA)
                && cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) 
                && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR));
    }
    

    You can also check if is the same date-time:

    public boolean isSameDateTime(Calendar cal1, Calendar cal2) {
        // compare if is the same ERA, YEAR, DAY, HOUR, MINUTE and SECOND
        return (cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA)
               && cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)
               && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR)
               && cal1.get(Calendar.HOUR_OF_DAY) == cal2.get(Calendar.HOUR_OF_DAY)
               && cal1.get(Calendar.MINUTE) == cal2.get(Calendar.MINUTE)
               && cal1.get(Calendar.SECOND) == cal2.get(Calendar.SECOND));
    }
    

提交回复
热议问题