如何使用DateTime :: createFromFormat在PHP中计算日期/时间之间的分钟数?

时间:2013-07-12 07:20:17

标签: php date datetime

使用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";

?>

2 个答案:

答案 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对象之间的差异