使用DateTime::createFromFormat
如何计算$dt1
与$dt2
之间的差异,以$dt2
为后期?
我尝试了$dt2 - $dt1
,但当然会产生error
。
<?php
date_default_timezone_set('America/New_York');
// $time1 will always be in HH:MM:SS MM/DD/YYYY format.
$time1 = "08:18:00 07/11/2013";
// $time2 will always be in MM/DD/YYYY HH:MM:SS format.
$time2 = "7/11/2013 9:11:00 AM";
$dt1 = DateTime::createFromFormat("H:i:s m/d/Y", $time1);
$dt2 = DateTime::createFromFormat("m/d/Y g:i:s a", $time2);
var_dump($dt1);
var_dump($dt2);
if ($dt1 < $dt2) echo "The first is earlier" . "\n";
?>
答案 0 :(得分:2)
$time1 = "08:18:00 07/11/2013";
$time2 = "7/11/2013 9:11:00 AM";
$dt1 = DateTime::createFromFormat("H:i:s m/d/Y", $time1);
$dt2 = DateTime::createFromFormat("m/d/Y g:i:s a", $time2);
$interval = $dt1->diff($dt2);
echo $interval->format("%i")." minutes";
答案 1 :(得分:0)
查看 DateTime::diff()
。
DateTime::diff
-DateTimeImmutable::diff
-DateTimeInterface::diff
-date_diff
- 返回两个DateTime对象之间的差异