java date 同一天_Java中判断两个Date是否是同一天

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 get and set indicating the * year. This is a calendar-specific value; see subclass documentation. */

public final static int YEAR = 1;

/** * Field number for get and set 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);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值