Java中判断两个Date是否是同一天
2017-11-04 12:40
786 查看
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); } }
相关文章推荐
- java判断两个日期是否为同一天
- java 判断两个日期是否为同一天
- Java中判断两个时间是否相隔一天
- 判断两个Date是否在同一天
- java 判断日期是否是同一天
- java 判断两个时间段是否有交集
- java Android 判断两个集合是否包含不同元素
- Java中判断两个Long类型是否相等
- 比较两个java.util.Date 的日期(年月日)是否相同(忽略时、分、秒)的多种方法
- 判断两个单链表是否相交--java实现
- 从零开始学习算法(Java实现)~~~~之字符串篇~~~判断两个字符串是否是颠倒字母顺序构成的
- Java判断两个二叉树是否相同
- java中判断两个字符串是否相等的问题
- java中如何判断两个日期是否是同一周
- java 判断两个字符串是否相等
- [java]用md5来判断两个文件是否完全相同 1. 前言
- 判断java中两个对象是否相等
- java中如何高效判断两个容器是否有相同元素(时间复杂度为O(1))
- java中判断两个字符串是否相等的问题
- 在java后台判断两个文件是否是同一文件