前言
Date是java.util包的一个日期(时间)工具类,几乎所有的系统业务都离不开它,前端展示、数据库存储及数据比较,日常数据查询也都会用到它。而程序里面经常会用到Date时间的先后顺序比较和判断,就如基本数字的大小比较一样,今天介绍一个比较隐秘的尝试,也是Date类本身提供的几个大小比较方法。
屌丝写法
由于写代码习惯了基本数据类型(int/Integer、long等)大小的比较,大多数人在对Date的时间先后比较也是用大小(>、<、>=、<=)。
getTime() 函数返回的是基本数据类型long,可以用>、<、=、>=、<= 来比较大小
Date date1 = new Date();
Date date2 = new Date();
date1.getTime() > date2.getTime(); // date1时间比date2时间大(所以date1比date2晚)
date1.getTime() < date2.getTime(); // date1时间比date2时间小(所以date1比date2早)
date1.getTime() == date2.getTime(); // date1时间和date2时间相等
高富帅写法
java中时间的大小比较:
准确的概念是时间的前后比较,在java中date并非大小之分。
java.util工具类的date原生提供了两个date比较的方法:
- before
- after
Date date1; //日期1
Date date2; //日期2
1、 date1.before(date2); //date1小于date2(date1比date2早)
2、 !(date1.before(date2)); //date1大于等于(date1比date2晚或相等),取1的补集
3、 date1.after(date2); //date1大于(date1比date2晚)
4、 !(date1.after(date2)); //date1小于等于date2(date1比date2早或相等),取3的补集
源码解析
调用before和after方法,可以看到getMillisOf(date)方法最终也是long的大小比较。
/**
* Tests if this date is before the specified date.
*
* @param when a date.
* @return <code>true</code> if and only if the instant of time
* represented by this <tt>Date</tt> object is strictly
* earlier than the instant represented by <tt>when</tt>;
* <code>false</code> otherwise.
* @exception NullPointerException if <code>when</code> is null.
*/
public boolean before(Date when) {
return getMillisOf(this) < getMillisOf(when);
}
/**
* Tests if this date is after the specified date.
*
* @param when a date.
* @return <code>true</code> if and only if the instant represented
* by this <tt>Date</tt> object is strictly later than the
* instant represented by <tt>when</tt>;
* <code>false</code> otherwise.
* @exception NullPointerException if <code>when</code> is null.
*/
public boolean after(Date when) {
return getMillisOf(this) > getMillisOf(when);
}
/**
* Returns the millisecond value of this <code>Date</code> object
* without affecting its internal state.
*/
static final long getMillisOf(Date date) {
if (date.cdate == null || date.cdate.isNormalized()) {
return date.fastTime;
}
BaseCalendar.Date d = (BaseCalendar.Date) date.cdate.clone();
return gcal.getTime(d);
}
注:date1和date2的2个日期,一定要是标准的日期格式:yyyyMMddHHmmss或yyyy-MM-dd HH:mm:ss
如果不是,在比较前一定要先格式化成这两种格式后再做比较,否则会抛异常。
既然都看完了整篇文章,相信对你一定有所帮助。原创不易,勿做伸手党。
点击下方【打赏】小编,或者关注公众号给予支持,你们的每一份鼓励都将是小编伟大的动力。