19
10

More than 5 years have passed since last update.

PHP: 2つのDateTimeが何秒差かを求める

Posted at

PHPで2つのDateTimeDateTimeImmutableオブジェクトの時刻の差が何秒か計算する方法を紹介する。

DateTime::getTimestampはUnixタイムスタンプを返すが、タイムスタンプは1970/1/1からの経過秒なので、両者のタイムスタンプを計算してあげればいい。

$startedOn = new DateTimeImmutable('2001-02-03 00:00:00.000000');
$finishedOn = new DateTimeImmutable('2001-02-03 01:01:01.123456');
$durationInSeconds = $finishedOn->getTimestamp() - $startedOn->getTimestamp();

// テスト
assert($durationInSeconds === 3661);

なお、DateTime::diffの戻り値のDateIntervalから求めるのは意外と大変。

$startedOn = new DateTimeImmutable('2001-02-03 00:00:00.000000');
$finishedOn = new DateTimeImmutable('2001-02-03 01:01:01.123456');
$diff = $finishedOn->diff($startedOn);
$durationInSeconds = ($diff->s)
            + ($diff->i * 60)
            + ($diff->h * 60 * 60)
            + ($diff->d * 60 * 60 * 24)
            + ($diff->m * 60 * 60 * 24 * 30) // 月は30でいいのか?
            + ($diff->y * 60 * 60 * 24 * 365); // 年は365でいいのか?
assert($durationInSeconds === 3661);
19
10
2

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