java中计算两个日期之间相差多少天
- 先将Date格式化为只有年、月、日的形式,返回String。然后将此String再转化为Date(此时时、分、秒就成为了00:00:00)
- 调用getTime()方法返回Date的1970的毫秒表示。将两个日期的毫秒相减,然后除以一天有(246060*1000)毫秒,得到日期差。
public static long getInterval(Date begin_date, Date end_date) throws ParseException {
long day = 0;
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
if(begin_date != null){
String begin = sdf.format(begin_date);
begin_date = sdf.parse(begin);
}else {
begin_date=sdf.parse(sdf.format(new Date()));
}
if(end_date!= null){
String end= sdf.format(end_date);
end_date= sdf.parse(end);
}else{
end_date=sdf.parse(sdf.format(new Date()));
}
long day = (end_date.getTime() - begin_date.getTime()) / (24 * 60 * 60 * 1000);
return day>=0?day:-day;
}
public static long getInterval(Date date) throws ParseException {
long day = 0;
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
if(date!= null){
String end= sdf.format(date);
date= sdf.parse(end);
}else{
throw new NullPointerException() ;
}
Date nowDate=sdf.parse(sdf.format(new Date()));
day = (date.getTime() - nowDate.getTime()) / (24 * 60 * 60 * 1000);
return day >= 0 ? day : -day;
}