MSSQL中提供了个datediff函数用来对两个时间进行减法操作,但在Java中却没有,如果我们想知道两个日期间相隔了多少天,或是相隔了多少个小时则要手工计算。下面代码模仿MSSQL的datediff函数提供了使用不同时间间隔来计算两个时间相差的时间间隔的数目,比如timeInterval为day则返回相差的天数,为month则返回相差的月数。总共支持year,quarter,month,week,day,hour,minute,second这几种时间间隔,date1和date2为要计算的两个时间,结果为date1减去date2后的值。
/**
* 按指定日期单位计算两个日期间的间隔
*
* @param timeInterval
* @param date1
* @param date2
* @return
*/
public static long dateDiff(String timeInterval, Date date1, Date date2) {
if (timeInterval.equals("year")) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date1);
int time = calendar.get(Calendar.YEAR);
calendar.setTime(date2);
return time - calendar.get(Calendar.YEAR);
}
if (timeInterval.equals("quarter")) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date1);
int time = calendar.get(Calendar.YEAR) * 4;
calendar.setTime(date2);
time -= calendar.get(Calendar.YEAR) * 4;
calendar.setTime(date1);
time += calendar.get(Calendar.MONTH) / 4;
calendar.setTime(date2);
return time - calendar.get(Calendar.MONTH) / 4;
}
if (timeInterval.equals("month")) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date1);
int time = calendar.get(Calendar.YEAR) * 12;
calendar.setTime(date2);
time -= calendar.get(Calendar.YEAR) * 12;
calendar.setTime(date1);
time += calendar.get(Calendar.MONTH);
calendar.setTime(date2);
return time - calendar.get(Calendar.MONTH);
}
if (timeInterval.equals("week")) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date1);
int time = calendar.get(Calendar.YEAR) * 52;
calendar.setTime(date2);
time -= calendar.get(Calendar.YEAR) * 52;
calendar.setTime(date1);
time += calendar.get(Calendar.WEEK_OF_YEAR);
calendar.setTime(date2);
return time - calendar.get(Calendar.WEEK_OF_YEAR);
}
if (timeInterval.equals("day")) {
long time = date1.getTime() / 1000 / 60 / 60 / 24;
return time - date2.getTime() / 1000 / 60 / 60 / 24;
}
if (timeInterval.equals("hour")) {
long time = date1.getTime() / 1000 / 60 / 60;
return time - date2.getTime() / 1000 / 60 / 60;
}
if (timeInterval.equals("minute")) {
long time = date1.getTime() / 1000 / 60;
return time - date2.getTime() / 1000 / 60;
}
if (timeInterval.equals("second")) {
long time = date1.getTime() / 1000;
return time - date2.getTime() / 1000;
}
return date1.getTime() - date2.getTime();
}