JavaのYearMonthクラス(年月)からLocalDate(年月日の1~末日)に変換する

JavaのYearMonthクラス(年月)からLocalDate(年月日の1~末日)に変換する

YearMonthクラスからLocalDateの1~末日のインスタンスを生成したい時のコーディングです。

package jp.co.confrage;

import java.time.LocalDate;
import java.time.YearMonth;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class SampleMain {
  public static void main(String[] args) {
    YearMonth yyyyMM = YearMonth.of(2019, 9);
    List list = IntStream
      .range(0,yyyyMM.lengthOfMonth())
      .mapToObj(e -> yyyyMM.atDay(1).plusDays(e)).collect(Collectors.toList());// 注
    list.forEach(e -> System.out.println(e));
  }
}

lengthOfMonth()メソッドは1月なら31を返し、9月なら30を返します。

atDay(1)メソッドは引数の日のLocalDateクラスのインスタンスを返します。

さらに、plusDays()メソッドは引数の日にちを足した結果のLocalDateクラスのインスタンスを返します。

mapToObjのeは0,1,2…というように30回実行されます。(2019年9月なので)

結果、list変数には2019年9月の1日~末日までのLocalDateクラスのインスタンスが入ります。

2019-09-01
2019-09-02
2019-09-03
2019-09-04
2019-09-05
2019-09-06
2019-09-07
2019-09-08
2019-09-09
2019-09-10
2019-09-11
2019-09-12
2019-09-13
2019-09-14
2019-09-15
2019-09-16
2019-09-17
2019-09-18
2019-09-19
2019-09-20
2019-09-21
2019-09-22
2019-09-23
2019-09-24
2019-09-25
2019-09-26
2019-09-27
2019-09-28
2019-09-29
2019-09-30

注:Java16から以下メソッド追加されました。

.collect(Collectors.toList());

.toList();

コメント

タイトルとURLをコピーしました