/**
* 獲取兩個日期之間的間隔天數(第二個日期必須大於第一個日期)
* @param t1 第一個時間 yyy-MM-dd
* @param t2 第二個時間 yyyy-MM-dd
* @return int 間隔天數
* @throws Exception
*/
private int getBetweenDays(String t1, String t2) throws Exception {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
int betweenDays = 0;
Date d1 = format.parse(t1);
Date d2 = format.parse(t2);
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.setTime(d1);
c2.setTime(d2);
// 保證第二個時間一定大於第一個時間
if (c1.after(c2)) {
c1 = c2;
c2.setTime(d1);
}
int betweenYears = c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR);
betweenDays = c2.get(Calendar.DAY_OF_YEAR)
- c1.get(Calendar.DAY_OF_YEAR);
for (int i = 0; i < betweenYears; i++) {
c1.set(Calendar.YEAR, (c1.get(Calendar.YEAR) + 1));
betweenDays += c1.getMaximum(Calendar.DAY_OF_YEAR);
}
return betweenDays;
}
獲取兩個日期之間的間隔天數
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.