Java中判断两个Date是否是同一天

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010412719/article/details/78442784

Java中判断两个Date是否是同一天

在Java中如何判断两个Data是否是同一天呢?

你可以选择自己借助于Calendar来实现(如何实现,可以参考下面将分析的commons-lang包的isSameDay方法),当然,你也可以选择借助于commons-lang3这个jar中的DateUtils.isSameDay方法来实现,下面这里看一下这个类的内部实现。

commons-lang3的版本为:3.3.2
org.apache.commons.lang3.time.DateUtils.isSameDay(Date date1, Date date2)方法的源码如下:

    public static boolean isSameDay(Date date1, Date date2) {
        if(date1 != null && date2 != null) {
            Calendar cal1 = Calendar.getInstance();
            cal1.setTime(date1);
            Calendar cal2 = Calendar.getInstance();
            cal2.setTime(date2);
            return isSameDay(cal1, cal2);
        } else {
            throw new IllegalArgumentException("The date must not be null");
        }
    }

    public static boolean isSameDay(Calendar cal1, Calendar cal2) {
        if(cal1 != null && cal2 != null) {
            return cal1.get(0) == cal2.get(0) && cal1.get(1) == cal2.get(1) && cal1.get(6) == cal2.get(6);
        } else {
            throw new IllegalArgumentException("The date must not be null");
        }
    }

其中,上面方法中的0、1、6的含义如下:

    public final static int ERA = 0;

    /**
     * Field number for <code>get</code> and <code>set</code> indicating the
     * year. This is a calendar-specific value; see subclass documentation.
     */
    public final static int YEAR = 1;



    /**
     * Field number for <code>get</code> and <code>set</code> indicating the day
     * number within the current year.  The first day of the year has value 1.
     */
    public final static int DAY_OF_YEAR = 6; 

到这里我们就明白了,commons-lang包中的isSameDay方法的实现思想为:利用是否是同一ERA(翻译成:世纪)且同一年的第N天来判断的。

这里还有一个小知识点:如何得到当前时间的明天零点时间,例如:当前时间为2017-11-03 12:33:20,得到的明天零点时间为2017-11-04 00:00:00。

实现这个小功能的具体代码如下:

    public class TestCalendar {

        public static void main(String[] args) {

            Date currentEndDate = new Date();
            Calendar cal = Calendar.getInstance();
            cal.setTime(currentEndDate);
            cal.add(Calendar.DATE, 1);
            cal.set(Calendar.AM_PM, 0);
            cal.set(Calendar.HOUR, 0);
            cal.set(Calendar.MINUTE, 0);
            cal.set(Calendar.SECOND, 0);
            Date nextDate = cal.getTime();

            System.out.println(nextDate);
        }
    }

猜你喜欢

转载自blog.csdn.net/u010412719/article/details/78442784