4
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?

More than 3 years have passed since last update.

PHP DateTime の差を小数点以下も含めて合計秒数を表示する

Last updated at Posted at 2020-01-30

環境

  • PHP 7.3

コード

$d1 = new DateTime('2020-01-01 12:00:00.123456');
$d2 = new DateTime('2021-02-03 14:50:06.654321');

$seconds = $d2->getTimestamp() - $d1->getTimestamp();
$decimal = $d1->diff($d2)->format('%f');
echo $seconds . '.' . $decimal;

// 34483806.530865

2020.01.30 追記

Carbonを使うとスマートに書けることを教えていただきました!

use Carbon\Carbon;

$d1 = new Carbon('2020-01-01 12:00:00.123456');
$d2 = new Carbon('2021-02-03 14:50:06.654321');

echo $d1->floatDiffInSeconds($d2);

// 34483806.530865

参考

4
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
4
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?