LoginSignup
0
0

More than 3 years have passed since last update.

【PHP】DateIntervalクラスで、あさってが「1日差」になっちゃった!?

Posted at

環境

CentOS 7.6
PHP 7.1.20

現象

PHPの DateInterval クラス は、
今日が 2020/01/01 とすると、2020/01/03 との日数差が
なぜか「1」で返る場合があります(2が欲しいのに。)

$date1 = new DateTime();             //今日
$date2 = new DateTime('2020-01-03'); //あさって
$diff = $date1->diff( $date2 );

echo $diff->days;  // 1

原因

今日の $date1 = new DateTime(); に現在時刻が含まれているからです。
その分、日数差が2日に届かず、1日となっているようです。

例えば 現在時刻をクリアすれば、期待する「2」が得られます。

$date1 = new DateTime();
$date1->setTime(0,0,0);  //時刻クリア

$date2 = new DateTime('2020-01-03');
$diff = $date1->diff( $date2 );

echo $diff->days; // 2

余談ですが、DateTime::diff のマニュアルには、
英語コメントに同様の記述がありました。

参考

PHPのDateTimeで日付差分を得る時は、dではなくdaysを使う。

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