Java計算兩日期之間的天數
阿新 • • 發佈:2018-11-15
public static int daysBetween(String early, String late){
Date earlydate = new Date();
Date latedate = new Date();
DateFormat df = DateFormat.getDateInstance();
try{
earlydate = df.parse(early);
latedate = df.parse(late);
}catch (Exception e){
e.printStackTrace();
}
java.util.Calendar calst = java.util.Calendar.getInstance();
java.util.Calendar caled = java.util.Calendar.getInstance();
calst.setTime(earlydate);
caled.setTime(latedate);
//設定時間為0時
calst.set(java.util.Calendar.HOUR_OF_DAY, 0);
calst.set(java.util.Calendar.MINUTE, 0);
calst.set(java.util.Calendar.SECOND, 0);
caled.set(java.util.Calendar.HOUR_OF_DAY, 0);
caled.set(java.util.Calendar.MINUTE, 0);
caled.set(java.util.Calendar.SECOND, 0);
//得到兩個日期相差的天數
int days = ((int) (caled.getTime().getTime() / 1000) - (int) (calst
.getTime().getTime() / 1000)) / 3600 / 24;
return days;
}
Date earlydate = new Date();
Date latedate = new Date();
DateFormat df = DateFormat.getDateInstance();
try{
earlydate = df.parse(early);
latedate = df.parse(late);
}catch (Exception e){
e.printStackTrace();
}
java.util.Calendar calst = java.util.Calendar.getInstance();
java.util.Calendar caled = java.util.Calendar.getInstance();
calst.setTime(earlydate);
caled.setTime(latedate);
//設定時間為0時
calst.set(java.util.Calendar.HOUR_OF_DAY, 0);
calst.set(java.util.Calendar.MINUTE, 0);
calst.set(java.util.Calendar.SECOND, 0);
caled.set(java.util.Calendar.HOUR_OF_DAY, 0);
caled.set(java.util.Calendar.MINUTE, 0);
caled.set(java.util.Calendar.SECOND, 0);
//得到兩個日期相差的天數
int days = ((int) (caled.getTime().getTime() / 1000) - (int) (calst
.getTime().getTime() / 1000)) / 3600 / 24;
return days;
}