2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHPの日付処理の落とし穴(+1 month)

2
Posted at

私が過去何度も落ちた穴です(今後も落ちないとは限らない)。
その穴とは、「ある日の次の月の末日」
これを書いている12月12日だったら来年1月の末日1月31日のことである。
どう穴に落ちるのか。
date()とCarbonで素直に書いてみる。

require 'vendor/autoload.php';

use Carbon\Carbon;

$d = date('Y-m-t', strtotime('2017-01-31 +1 month'));
echo 'date => '.$d.PHP_EOL;

$c = Carbon::parse('2017-01-31')->addMonth(1)->endOfMonth();
echo 'Carbon => '.$c->format('Y-m-d').PHP_EOL;

// 実行結果
// date => 2017-03-31
// Carbon => 2017-03-31

素直に穴に落ちた。
ここで正解として求められているのは2017-02-28である。
修正案としては以下コード。

require 'vendor/autoload.php';

use Carbon\Carbon;

$d = date('Y-m-d', strtotime('2017-01-31 last day of +1 month'));
echo 'date => '.$d.PHP_EOL;

$c = Carbon::parse('2017-01-31')->firstOfMonth()->addMonth(1)->endOfMonth();
echo 'Carbon => '.$c->format('Y-m-d').PHP_EOL;

// 実行結果
// date => 2017-02-28
// Carbon => 2017-02-28

date()のほうが記述がシンプルですね。
Carbonはもっといい方法があったりするのでしょうか。。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?