经常会有一些需求,要求检查两个日期之间相隔的天数。方便起见就写成一个静态函数,并且不区分前后日期,使用绝对值。
/**
* 获取两个日期的相差天数(自然日)只计算日期,所以清除时分秒
*/
public static Long getDaysBetween(Date startDate, Date endDate) {
Calendar fromCalendar = Calendar.getInstance();
fromCalendar.setTime(startDate);
fromCalendar.set(Calendar.HOUR_OF_DAY, 0);
fromCalendar.set(Calendar.MINUTE, 0);
fromCalendar.set(Calendar.SECOND, 0);
fromCalendar.set(Calendar.MILLISECOND, 0);
Calendar toCalendar = Calendar.getInstance();
toCalendar.setTime(endDate);
toCalendar.set(Calendar.HOUR_OF_DAY, 0);
toCalendar.set(Calendar.MINUTE, 0);
toCalendar.set(Calendar.SECOND, 0);
toCalendar.set(Calendar.MILLISECOND, 0);
Long DaysBetween = (toCalendar.getTime().getTime() - fromCalendar.getTime().getTime()) / (1000 * 60 * 60 * 24);
return Math.abs(DaysBetween);
}
网友评论