現在有這樣一個需求:
統計兩個日期時間段每個月對應的天數
比如:2017-03-12 ~ 2018-12-18
2017-03-12到該月月底共有多少天
2017-04-01到該月月底有多少天
。。。
代碼實作:
/**
* Created by hjz on 2017/8/7 0007.
* Describe:
* 統計兩個日期時間段每個月對應的天數
* 比如:2017-03-12 ~ 2018-12-18
* 2017-03-12到該月月底共有多少天
* 2017-04該月有多少天
* 。。。
*/
public class TimeUtils {
public static void main(String[] args) throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
// Date maxDate = sdf.parse("2017-12-23");
Date maxDate = sdf.parse("2015-12-12");
Date minDate = sdf.parse("2015-12-12");
Calendar max = Calendar.getInstance();
max.setTime(maxDate);
max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);
Calendar min = Calendar.getInstance();
min.setTime(minDate);
min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);
Calendar curr = min;
List<Date> result = new ArrayList<>();
while (curr.before(max)) {
result.add(curr.getTime());
curr.add(Calendar.MONTH, 1);
}
String day = "";
Date minMothDate = null;
Date maxMothDate = null;
Calendar currMonthCal = Calendar.getInstance();
for (int i=0; i<result.size(); i++){
if (i == 0){ //處理開始日期時間
if (result.size() == 1){ //處理開始時間和結束時間是同年同月的情況
minMothDate = minDate;
maxMothDate = maxDate;
}else {
minMothDate = minDate;
currMonthCal.setTime(result.get(i));
//設定目前月最後一天
currMonthCal.set(Calendar.DAY_OF_MONTH, currMonthCal.getActualMaximum(Calendar.DAY_OF_MONTH));
maxMothDate = currMonthCal.getTime();
}
day = getTwoDay(maxMothDate,minMothDate);
}else if (i == result.size()-1){ //處理最後一次時間
maxMothDate = maxDate;
currMonthCal.setTime(result.get(i));
currMonthCal.set(Calendar.DAY_OF_MONTH,1);//設定為1号,目前日期既為本月第一天
minMothDate = currMonthCal.getTime();
day = getTwoDay(maxMothDate,minMothDate);
}else{
currMonthCal.setTime(result.get(i));
currMonthCal.set(Calendar.DAY_OF_MONTH,1);//設定為1号,目前日期既為本月第一天
minMothDate = currMonthCal.getTime();
//設定目前月最後一天
currMonthCal.set(Calendar.DAY_OF_MONTH, currMonthCal.getActualMaximum(Calendar.DAY_OF_MONTH));
maxMothDate = currMonthCal.getTime();
day = getTwoDay(maxMothDate,minMothDate);
}
System.out.println(currMonthCal.get(Calendar.YEAR )+"年"+(currMonthCal.get(Calendar.MONTH )+1)+"月共 "+day +" 天");
}
}
/**
* 得到二個日期間的間隔天數
* @param endTime 結束時間
* @param startTime 開始時間
* @return
*/
public static String getTwoDay(Date endTime, Date startTime) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
System.out.println( "startTime="+format.format(startTime)+ " endTime="+format.format(endTime) );
long day = 0;
try {
day = (endTime.getTime() - startTime.getTime()) / (24 * 60 * 60 * 1000)+1;
} catch (Exception e) {
return "";
}
return day + "";
}
}