Java8 獲取兩個日期之間的每一天


    /** * 收集起始時間到結束時間之間所有的時間並以字符串集合方式返回 * * @param type 1 獲取年月日 2 獲取月日 * @param timeStart 年月日 * @param timeEnd 年月日 * @return */
    public static List<String> collectLocalDates(String timeStart, String timeEnd, String type) {
        if ("2".equals(type)) {
            return collectLocalDates(LocalDate.parse(timeStart), LocalDate.parse(timeEnd), type);
        } else {
            return collectLocalDates(LocalDate.parse(timeStart), LocalDate.parse(timeEnd), type);
        }
    }

    /** * 收集起始時間到結束時間之間所有的時間並以字符串集合方式返回 * * @param type 1 獲取年月日 2 獲取月日 * @param start * @param end * @return */
    public static List<String> collectLocalDates(LocalDate start, LocalDate end, String type) {
        if ("2".equals(type)) {
            // 用起始時間作為流的源頭,按照每次加一天的方式創建一個無限流
            return Stream.iterate(start, localDate -> localDate.plusDays(1))
                    // 截斷無限流,長度為起始時間和結束時間的差+1個
                    .limit(ChronoUnit.DAYS.between(start, end) + 1)
                    // 由於最后要的是字符串,所以map轉換一下
                    .map(DateTimeUtil::getMonthAndDay)
                    // 把流收集為List
                    .collect(Collectors.toList());
        } else {
            // 用起始時間作為流的源頭,按照每次加一天的方式創建一個無限流
            return Stream.iterate(start, localDate -> localDate.plusDays(1))
                    // 截斷無限流,長度為起始時間和結束時間的差+1個
                    .limit(ChronoUnit.DAYS.between(start, end) + 1)
                    // 由於最后要的是字符串,所以map轉換一下
                    .map(LocalDate::toString)
                    // 把流收集為List
                    .collect(Collectors.toList());
        }
    }

    public static String getMonthAndDay(LocalDate localDate) {
        int monthValue = localDate.getMonthValue();
        String month = monthValue < 10 ? "0" + monthValue : monthValue + "";
        int dayOfMonth = localDate.getDayOfMonth();
        String day = dayOfMonth < 10 ? "0" + dayOfMonth : dayOfMonth + "";
        return month + "-" + day;
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM