LoginSignup
3
4

More than 3 years have passed since last update.

【Java】過去週の月曜日と日曜日の日付を順番に取得する

Last updated at Posted at 2019-06-24

やりたいこと

取得対象が過去3ヶ月の場合
今週:現在日が含まれる週の月曜日、日曜日の日付を取得
過去の週:各週の月曜日、日曜日の日付を取得
最終週:3ヶ月前の日付が含まれる週の月曜日、日曜日の日付を取得

ソース

swordone様から指摘をいただき、ロジックを修正しました(6/25)。 ※コメント参照

public static void main(String[] args) {

        // 現在日付を取得
        LocalDate now = LocalDate.now();

        // 3ヶ月前(この日付は適宜変える。この例では3ヶ月としている)の日付を取得
        LocalDate targetDate = now.minusMonths(3);

        // 現在日の週の月曜日を取得
        LocalDate monday = now.with(DayOfWeek.MONDAY);

        // 現在日の週の日曜日を取得
        LocalDate sunday = now.with(DayOfWeek.SUNDAY);

        int i = 0;
        while (!sunday.isBefore(targetDate)) {
            System.out.println(monday + " ~ " + sunday + " : " + (i == 0 ? "今週" : i + "週前"));
            monday = monday.minusDays(7);
            sunday = sunday.minusDays(7);
            i++;
        }
    }

実行結果

現在日は6/25です。取得対象は3ヶ月前までとしています。
過去数週間分で期間指定したい場合等に使えると思います。
取得対象の日付を適宜変更して使います。
※Java8のjava.time APIを使用しているので、Java7以前のバージョンでは使用不可です。

2019-06-24 ~ 2019-06-30 : 今週
2019-06-17 ~ 2019-06-23 : 1週前
2019-06-10 ~ 2019-06-16 : 2週前
2019-06-03 ~ 2019-06-09 : 3週前
2019-05-27 ~ 2019-06-02 : 4週前
2019-05-20 ~ 2019-05-26 : 5週前
2019-05-13 ~ 2019-05-19 : 6週前
2019-05-06 ~ 2019-05-12 : 7週前
2019-04-29 ~ 2019-05-05 : 8週前
2019-04-22 ~ 2019-04-28 : 9週前
2019-04-15 ~ 2019-04-21 : 10週前
2019-04-08 ~ 2019-04-14 : 11週前
2019-04-01 ~ 2019-04-07 : 12週前
2019-03-25 ~ 2019-03-31 : 13週前
3
4
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4