如何计算两个日期的差异

时间:2015-05-09 05:08:39

标签: php date

我在变量$ date1和$ date2中分配了两个日期。 这是代码..

if (isset($_POST['check_in']))
{
 $date1=date('Y-m-d', strtotime($_POST['check_in']));
}
if (isset($_POST['check_in']))
{
 $date2=date('Y-m-d', strtotime($_POST['check_out']));
}

例如,如果date1="2015-05-21"date2="2015-05-23"。我希望日期的差异为2

3 个答案:

答案 0 :(得分:1)

使用DateTime课程。试试 -

$date1=new DateTime("2015-05-21");
$date2=new DateTime("2015-05-23");

$interval = $date1->diff($date2);
echo $interval->format('%R%a days');

<强>输出

+2 days

DateTime()

答案 1 :(得分:0)

你走了:

https://php.net/manual/en/datetime.diff.php

代码包含各种示例。

这是我喜欢的一个:

<?php
$datetime1 = date_create('2015-05-21');
$datetime2 = date_create('2015-05-23');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%R%a days');
?>

我希望这会有所帮助:)

答案 2 :(得分:0)

由于strtotime返回unixtime,因此只需从另一个中减去一个strtotime即可计算出以秒为单位的差异:

$seconds = strtotime($_POST['check_out']) - strtotime($_POST['check_in']);

然后找到日子:

$days = $seconds / 60 / 60 / 24;
相关问题