LoginSignup
16
6

More than 5 years have passed since last update.

PHP 7.1からDateTimeが現在時刻のマイクロ秒まで見るようになった

Last updated at Posted at 2016-12-23

表題の通りですが、PHP 7.1からDateTimeおよびDateTimeImmutableの挙動が変わり、現在時刻にマイクロ秒まで反映されるようになりました。日付文字列を相対的な書式で与えた場合も同様にマイクロ秒が反映されます。

<?php
$dt1 = new DateTime();
$dt2 = new DateTime("first day of next month");
$dt3 = new DateTime("2016-12-24");
var_dump($dt1->format("Y-m-d H:i:s.u")); // string(26) "2016-12-24 06:59:17.930886"
var_dump($dt2->format("Y-m-d H:i:s.u")); // string(26) "2017-01-01 06:59:17.931709"
var_dump($dt3->format("Y-m-d H:i:s.u")); // string(26) "2016-12-24 00:00:00.000000"

PHP 7.0.x以前ではマイクロ秒を明示的にコンストラクタ引数として与えたときだけマイクロ秒がセットされていました。つまり、上の例であれば2016-12-24 06:59:17.000000などを返していました。

この変更のため、DateTime同士を比較するようなテストコードが動かなくなることがあるかもしれません1。このことはPHPマニュアルにも書いてあります(「DateTime constructor incorporates microseconds」)。


  1. この変更で影響を受けるテストコードは元々秒またぎのバグを抱えている気がしますが… 

16
6
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
16
6