LoginSignup
4
2

More than 3 years have passed since last update.

Carbon で1週間の日付と曜日を取得する

Posted at

PHPのCarbonで、日付と曜日(日本語)のリストを取得する方法をシェアします。

実行環境

  • Laravel Framework 6.18.23
  • "nesbot/carbon": "2.0"

取得したい結果

array: [
    0 => "10/18 (日)"
    1 => "10/19 (月)"
    2 => "10/20 (火)"
    3 => "10/21 (水)"
    4 => "10/22 (木)"
    5 => "10/23 (金)"
    6 => "10/24 (土)"
]

ソースコード

Laravelの config/app.php'locale' => 'ja' の設定しておく。

$numOfDays = 7; //日付を取得する日数

$dt = new Carbon();
$format = 'MM/DD (ddd)';

$week[0] = $dt->today()->isoFormat($format);

//Carbonのインスタンスが上書きされないようにcopy()して日付を加算
for ($i=1; $i < $numOfDays ; $i++) {
  $week[$i] = $dt->copy()->addDay($i)->isoFormat($format);
}

dump($week);

参考

https://carbon.nesbot.com/docs/
https://uiuifree.com/blog/develop/php-carbon-ja-weekday/

4
2
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
4
2