JAVA计算两个日期相差多少天
前言
有时候我们在JAVA中会比较两个日期相差多少天
,这里有几个实现方法供大家参考,偶尔会用到,也当做自己收藏。btw,同时也要鄙视一下我的好基友从百度搜到的一个答案的作者,写了毒代码,计算个日期而已,竟然要遍历两个日期的time。
解决方案
有使用Calendar
的,也有使用Date
的,都ok。但是基本都是去获取Time进行计算。Calendar也可以换成LocalCalendar等等的。
/** * JAVA计算两个日期相差多少天(by date) * @author zhengkai.blog.csdn.net */
public static int daysBetween(Date date1,Date date2){
Calendar cal = Calendar.getInstance();
cal.setTime(date1);
long time1 = cal.getTimeInMillis();
cal.setTime(date2);
long time2 = cal.getTimeInMillis();
long between_days=(time2-time1)/(1000*3600*24);
return Integer.parseInt(String.valueOf(between_days));
}
/** * JAVA计算两个日期相差多少天(by Date String with format "yyyy-MM-dd") * @author zhengkai.blog.csdn.net */
public static int daysBetween(String date1str,String date2str){
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = format.parse(date1str);
Date date2 = format.parse(date2str);
int a = (int) ((date1.getTime() - date2.getTime()) / (1000*3600*24));
return a;
}
/** * JAVA比较两个日期(使用hutool库的DateUtil) * @author zhengkai.blog.csdn.net */
if(DateUtil.compare(date1,date2)>0){
//如果date1>=date2
}else{
//如果date1<date2
}
批斗
以下是 有害代码,引以为戒
。真的是一天一天去遍历的…
public static int getDaysForTwoDate2(Date firstDate,Date secondDdate) throws ParseException {
Calendar calendar = Calendar.getInstance();
calendar.setTime(firstDate);
int cnt = 0;
while(calendar.getTime().compareTo(secondDdate)>0){
calendar.add(Calendar.DATE, 1);
cnt++;
}
System.out.println(cnt);
return cnt;
}
还没有评论,来说两句吧...