Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
1
Help us understand the problem. What is going on with this article?

More than 1 year has passed since last update.

@hidakanoko

[Java1.8+]LocalDateで次の×曜日の日付を取得する

TemporalAdjustersnext(DayOfWeek dayOfWeek)メソッドが返すTemporalAdjusterのインスタンスを使ってLocalDateの日付を次のx曜日の日付に変更できます。

サンプルコード

LocalDate d = LocalDate.of(2019, 3, 25).with(TemporalAdjusters.next(DayOfWeek.MONDAY));
LocalDate d2 = LocalDate.of(2019, 3, 29).with(TemporalAdjusters.next(DayOfWeek.valueOf("MONDAY")));
LocalDate d3 = LocalDate.of(2019, 3, 31).with(TemporalAdjusters.next(DayOfWeek.of(1)));

 System.out.println(d.toString());
 System.out.println(d2.toString());
 System.out.println(d3.toString());

出力

2019-04-01
2019-04-01
2019-04-01

LocalDateの日付がすでにその曜日の場合、翌週の日付に設定されます。

nextOrSame(DayOfWeek dayOfWeek)を使用すると、LocalDateがすでにその曜日である場合何もしません。

サンプル

LocalDate d = LocalDate.of(2019, 3, 25).with(TemporalAdjusters.nextOrSame(DayOfWeek.MONDAY));
LocalDate d2 = LocalDate.of(2019, 3, 29).with(TemporalAdjusters.nextOrSame(DayOfWeek.valueOf("MONDAY")));
LocalDate d3 = LocalDate.of(2019, 3, 31).with(TemporalAdjusters.nextOrSame(DayOfWeek.of(1)));

出力

2019-03-25
2019-04-01
2019-04-01
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
1
Help us understand the problem. What is going on with this article?