如何计算两个日期的差异[重复]

时间:2021-05-21 21:31:45

This question already has an answer here:

这个问题在这里已有答案:

I have two dates assigned in variable $date1 and $date2.. Here is the code..

我在变量$ 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']));
}

For example if date1="2015-05-21" and date2="2015-05-23".I want the difference of date as 2

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

3 个解决方案

#1


Use DateTime class. Try with -

使用DateTime类。尝试 -

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

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

Output

+2 days

DateTime()

#2


Since strtotime returns unixtime, the difference in seconds can be calculated by simply subtracting the one strtotime from the other:

由于strtotime返回unixtime,因此可以通过简单地从另一个中减去一个strtotime来计算秒的差异:

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

Then to find the days:

然后找到日子:

$days = $seconds / 60 / 60 / 24;

#3


Here you go:

干得好:

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

Code with various examples.

代码有各种例子。

Here's one I like:

这是我喜欢的一个:

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

I hope this helps :)

我希望这有帮助 :)

#1


Use DateTime class. Try with -

使用DateTime类。尝试 -

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

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

Output

+2 days

DateTime()

#2


Since strtotime returns unixtime, the difference in seconds can be calculated by simply subtracting the one strtotime from the other:

由于strtotime返回unixtime,因此可以通过简单地从另一个中减去一个strtotime来计算秒的差异:

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

Then to find the days:

然后找到日子:

$days = $seconds / 60 / 60 / 24;

#3


Here you go:

干得好:

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

Code with various examples.

代码有各种例子。

Here's one I like:

这是我喜欢的一个:

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

I hope this helps :)

我希望这有帮助 :)