LoginSignup
9
7

More than 5 years have passed since last update.

CarbonPeriodを使って期間を指定して途中の日付を柔軟に補完する

Last updated at Posted at 2018-12-19

CarbonPeriodを使って指定した期間の日付を楽に取得出来ます。

CarbonPeriodはCarbon 1.29から利用出来るようになっているようなので、現行バージョンのlaravelなら問題なく利用出来ると思います。

必要に駆られたら思い出して是非利用してみてください。

特定の期間を日単位で取得する

例えば任意の期間を日単位に配列で取得したい場合は、以下のように記載します。

$period = CarbonPeriod::create('2018-12-01', '2019-12-31');

foreach ($period as $date) {
    echo $date->format('Y-m-d') . "\n";
}

結果

2018-12-01
2018-12-02
2018-12-03
2018-12-04
2018-12-05
        ・
   途中省略
        ・
2018-12-27
2018-12-28
2018-12-29
2018-12-30
2018-12-31

特定の期間を月単位で取得する

月毎の配列を取得する場合も、months()を呼ぶ事で簡単に月単位になります。
その他、years、weeks、hours、minutes、secondsと状況に応じて柔軟に期間も指定できます。

$period = CarbonPeriod::create('2018-04-01', '2019-03-01')->months();

foreach ($period as $date) {
    echo $date->format('Y-m-d') . "\n";
}
2018-04-01
2018-05-01
2018-06-01
        ・
   途中省略
        ・
2019-01-01
2019-02-01
2019-03-01

配列に変換する

toArray()メソッドを使えば、そのまま配列として利用出来ます。

$period = CarbonPeriod::create('2018-04-01', '2018-04-15')->toArray();

collect($period)->map(function ($date) {
    return $date->format('Y-m-d');
})->dd();

結果

Illuminate\Support\Collection {#780
  #items: array:15 [
    0 => "2018-04-01"
    1 => "2018-04-02"
    2 => "2018-04-03"
    3 => "2018-04-04"
    4 => "2018-04-05"
    5 => "2018-04-06"
    6 => "2018-04-07"
    7 => "2018-04-08"
    8 => "2018-04-09"
    9 => "2018-04-10"
    10 => "2018-04-11"
    11 => "2018-04-12"
    12 => "2018-04-13"
    13 => "2018-04-14"
    14 => "2018-04-15"
  ]
}

それではごきげんよう!!

9
7
0

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
9
7