Help us understand the problem. What is going on with this article?

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

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/

hdmt
#Laravel #React #フリーランス
https://wpcustom.info/
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