OStack程序员社区-中国程序员成长平台

标题: datetime - How to calculate the difference between two dates using PHP? [打印本页]

作者: 菜鸟教程小白    时间: 2022-4-10 16:07
标题: datetime - How to calculate the difference between two dates using PHP?

I have two dates of the form:

Start Date: 2007-03-24 
End Date: 2009-06-26

Now I need to find the difference between these two in the following form:

2 years, 3 months and 2 days

How can I do this in PHP?



Best Answer-推荐答案


I suggest to use DateTime and DateInterval objects.

$date1 = new DateTime("2007-03-24");
$date2 = new DateTime("2009-06-26");
$interval = $date1->diff($date2);
echo "difference " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days "; 

// shows the total amount of days (not divided into years, months and days like above)
echo "difference " . $interval->days . " days ";

read more php DateTime::diff manual

From the manual:

As of PHP 5.2.2, DateTime objects can be compared using comparison operators.

$date1 = new DateTime("now");
$date2 = new DateTime("tomorrow");

var_dump($date1 == $date2); // bool(false)
var_dump($date1 < $date2);  // bool(true)
var_dump($date1 > $date2);  // bool(false)





欢迎光临 OStack程序员社区-中国程序员成长平台 (http://ostack.cn/) Powered by Discuz! X3.4