32
19

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のDateTimeで日付差分を得る時は、dではなくdaysを使う。

Posted at

最初、以下のように、日数を算出していた。

sample1.php
$day = new DateTime('2018-04-05');
$day2 = new DateTime('2018-04-11');
$diff = $day->diff($day2);
echo diff->d;

結果: 6

が、この場合だと、日だけを見て差分を見ているので、月が変わっても結果は同じになってしまう。

sample2.php
$day = new DateTime('2018-03-05');
$day2 = new DateTime('2018-04-11');
$diff = $day->diff($day2);
echo diff->d;

結果: 6 ← 本来なら37日が正しい

年月を含めて日数を見るなら

sample3.php
$day = new DateTime('2018-03-05');
$day2 = new DateTime('2018-04-11');
$diff = $day->diff($day2);
echo diff->days;

結果: 37

日数を算出する場合は、dではなく、daysを使う。

32
19
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
32
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?