0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Laravel】Carbonで日時操作する時に気を付けること

Last updated at Posted at 2024-10-07
  • Carbon/Carbon

通常のCarbonmutable(変更可能)なので作成したインスタンスが書き換えられてしまう。

<?php
use Carbon/Carbon;

$now = Carbon::now();
$tomorrow = $now->addDay();

echo $now->format('Y/m/d H:i:s') // "2023/02/22 12:14:00"
echo $tomorrow->format('Y/m/d H:i:s') // "2023/02/22 12:14:00"
  • Carbon\CarbonImmutable

CarbonImmutableは(変更不可能)なので作成したインスタンスは値が保持される。

<?php
use Carbon/CarbonImmutable;

$now = CarbonImmutable::now();
$tomorrow = $now->addDay();

echo $now->format('Y/m/d H:i:s') // "2023/02/21 12:14:00"
echo $tomorrow->format('Y/m/d H:i:s') // "2023/02/22 12:14:00"

Carbonクラスでもcopy()で最初に作成したインスタンスをコピーできる。
※書き忘れなどが生じるためCarbonImmutable推奨

<?php
use Carbon/Carbon;

$now = Carbon::now();
$tomorrow = $now->copy()->addDay();

echo $now->format('Y/m/d H:i:s') // "2023/02/21 12:14:00"
echo $tomorrow->format('Y/m/d H:i:s') // "2023/02/22 12:14:00"

結論

CarbonImmutableを使用した方が、思わぬエラーを回避できる

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?