JAVA獲取兩個日期之間的所有日期(包含開始時間和結束時間)

    /**
     * 
     * @description: 獲取兩個日期之間的所有日期(參數及返回日期均爲字符串格式)
     * @param startTime 開始日期
     * @param endTime 結束日期
     * @return List<String> 日期集合
     * @throws ParseException 
     */

    public static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    public static List<String> getTimesBetweenDates(String startTime, String endTime) throws ParseException {
        Date start = dateFormat.parse(startTime);
        Date end = dateFormat.parse(endTime);
        System.out.println(startTime + "***" + endTime);
        // 如果時間傳反了
        long time1 = start.getTime();
        long time2 = end.getTime();
        Date midTime = new Date();
        if (time1 > time2) {
            midTime = start;
            start = end;
            end = midTime;
        }
        List<String> result = new ArrayList<String>();
        Calendar startCal = Calendar.getInstance();
        startCal.setTime(start);

        Calendar endCal = Calendar.getInstance();
        endCal.setTime(end);
        endCal.add(Calendar.DATE, +1);// 日期+1,將結束日期放入結果集
        while (startCal.before(endCal)) {
            result.add(formatDate(startCal.getTime()));
            startCal.add(Calendar.DAY_OF_YEAR, 1);
        }
        return result;
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章