1

I've always used the code below to calculate the difference (in days) between two dates. But I'm wondering if there is something more intelligent, someone knows a better way to do this?

//86400 one day
$data1 = '2013-07-24 21:30:00';
$data2 = '2013-08-24 21:30:00';

$diff =  (abs(strtotime($data1) - strtotime($data2))) / 86400;

var_dump($diff);
4

1 回答 1

6

您可以使用DateTime:diff

$data1 = new DateTime('2013-07-24 21:30:00');
$data2= new DateTime('2013-08-24 21:30:00');
$interval = $data1->diff($data2);
echo $interval->format('%R%a days');

如果您的输入日期具有不同的格式,您还可以使用DateTime::createFromFormat以获得更好的结果,例如:

$date1 = DateTime::createFromFormat('Y-m-d H:i:s', '2013-07-24 21:30:00');
$date2 = DateTime::createFromFormat('Y-m-d H:i:s', '2013-08-24 21:30:00');
$interval = $date1->diff($date2);
echo $interval->format('%R%a days');
于 2013-07-25T01:12:57.793 回答