指定した時間内に曜日を指定したすべての日付を取得

13247 ワード

開始時間、終了時間、曜日、3つのパラメータを入力し、この2つの日付の間に曜日を指定する日付を取得します.

一.パラメータ宣言:

LocalDate start = LocalDate.of(2020, 4, 1);
LocalDate end = LocalDate.of(2020, 5, 1);
int week = 1;

二.テスト:

/**
 *  
 * @Author liuwenxu.com (2020-04-26)
 *
 * @param start   2020-04-01
 * @param end     2020-05-01
 * @param week    1
 * @return ArrayList [2020-04-06, 2020-04-13, 2020-04-20, 2020-04-27]
 */
public static List getWeekInTimes(LocalDate start, LocalDate end, int week) {
    ArrayList<LocalDate> list = new ArrayList<>();

    long days = ChronoUnit.DAYS.between(start, end);
    log.info("[{}~{}) :{} ", start, end, days);

    Calendar startCalender = GregorianCalendar.from(start.atStartOfDay(ZoneId.systemDefault()));
    for (int i = 0; i < days - 1; i++) {
        startCalender.add(Calendar.DATE, 1);

        if (startCalender.get(Calendar.DAY_OF_WEEK) == week + 1) {// 1 ,7 
            list.add(
                    LocalDateTime.ofInstant(
                            startCalender.toInstant(),
                            ZoneOffset.systemDefault()
                    ).toLocalDate()
            );
        }
    }
    log.info("[{}~{}) :{}   {}", start, end, list.size(), week);
    return list;
}

三.結果

- [2020-04-01~2020-05-01) :30 
- [2020-04-01~2020-05-01) :4   1
[2020-04-06, 2020-04-13, 2020-04-20, 2020-04-27]

四.広がる


その月のすべての週末の日付を取得

    /**
     *  
     * @Author liuwenxu.com (2020-04-26)
     *
     * @param year  2020
     * @param month 4
     * @return 
     */
    public static List getWeekendInMonth(int year, int month) {

        List list = new ArrayList();
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);//  
        calendar.set(Calendar.MONTH, month - 1);//  
        calendar.set(Calendar.DAY_OF_MONTH, 1);//  
        int daySize = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);//  
        for (int i = 0; i < daySize - 1; i++) {
            calendar.add(Calendar.DATE, 1);// 1
            int week = calendar.get(Calendar.DAY_OF_WEEK);
            if (week == Calendar.SATURDAY || week == Calendar.SUNDAY) {// 1 ,7   
                list.add(year + "-" + month + "-" + calendar.get(Calendar.DAY_OF_MONTH));//  
            }
        }
        return list;
    }

結果:

[2020-4-4, 2020-4-5, 2020-4-11, 2020-4-12, 2020-4-18, 2020-4-19, 2020-4-25, 2020-4-26]

添付:コード元ファイル