「PHP」diff()で時間の差分を求めるサンプル

2021年4月15日

書式
public DateTime::diff ( DateTimeInterface $targetObject [, bool $absolute = FALSE ] ) : DateInterval
使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
$dtA = new DateTime('2021-02-11 11:10:10');
$dtB = new DateTime('2021-04-13 13:00:00');
$res = $dtA->diff($dtB);
//h 時間
echo $res->days*24 + $res->h;
$dtC = new DateTime('2021-01-01 10:00:00');
$dtD = new DateTime('2021-01-03 13:30:00');
$resB = $dtC->diff($dtD);
//h 時間 i分
echo $resB->days*24*60 + $resB->h*60 + $resB->i;
?>
<?php $dtA = new DateTime('2021-02-11 11:10:10'); $dtB = new DateTime('2021-04-13 13:00:00'); $res = $dtA->diff($dtB); //h 時間 echo $res->days*24 + $res->h; $dtC = new DateTime('2021-01-01 10:00:00'); $dtD = new DateTime('2021-01-03 13:30:00'); $resB = $dtC->diff($dtD); //h 時間 i分 echo $resB->days*24*60 + $resB->h*60 + $resB->i; ?>
<?php

$dtA = new DateTime('2021-02-11 11:10:10');
$dtB = new DateTime('2021-04-13 13:00:00');

$res = $dtA->diff($dtB);
//h 時間
echo $res->days*24 + $res->h; 

$dtC = new DateTime('2021-01-01 10:00:00');
$dtD = new DateTime('2021-01-03 13:30:00');
$resB = $dtC->diff($dtD);
//h 時間 i分
echo $resB->days*24*60 + $resB->h*60 + $resB->i;
?>

 

PHP

Posted by arkgame