JAVA 獲取某個時間段內所有的日期
阿新 • • 發佈:2019-01-07
輸入格式:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date dBegin = sdf.parse("2017-03-03");
Date dEnd = sdf.parse("2017-06-04");
List<String> datas = findDates(dBegin, dEnd);
輸出list->20170303,20170304,20170305。。。
public List<String> findDates(Date dBegin, Date dEnd){ List<String> lDate = new ArrayList<String>(); SimpleDateFormat sd = new SimpleDateFormat("yyyyMMdd"); lDate.add(sd.format(dBegin)); Calendar calBegin = Calendar.getInstance(); // 使用給定的 Date 設定此 Calendar 的時間 calBegin.setTime(dBegin); Calendar calEnd = Calendar.getInstance(); // 使用給定的 Date 設定此 Calendar 的時間 calEnd.setTime(dEnd); // 測試此日期是否在指定日期之後 while (dEnd.after(calBegin.getTime())) { // 根據日曆的規則,為給定的日曆欄位新增或減去指定的時間量 calBegin.add(Calendar.DAY_OF_MONTH, 1); lDate.add(sd.format(calBegin.getTime())); } return lDate; }