我想用PHP计算月份中两个日期之间的差异,但似乎某处存在错误。
$datetime1 = new DateTime(date('Y-m-d'));
$datetime2 = new DateTime(MyObject->getDate());
echo($datetime1->format('d/m/Y'));
echo($datetime2->format('d/m/Y));
结果:
29/01/2016
27/01/2015
$dateInterval = $datetime1->diff($datetime2);
echo($dateInterval->format(%m months);
结果:
0 months
为什么?我做错了什么?
答案 0 :(得分:2)
计算两个日期之间的月份:
对于 PHP> = 5.3 ,您可以使用返回a的DateTime diff DateInterval对象如下。
$d1 = new DateTime("2013-12-09"); $d2 = new DateTime("2014-03-17"); var_dump($d1->diff($d2)->m); var_dump($d1->diff($d2)->m + ($d1->diff($d2)->y*12));
如果您没有PHP 5.3或更高版本,则可以使用
strtotime()
函数获取时间戳,任何日期和之间的秒数 1970年1月1日00:00:00。$d1 = "2013-12-09"; $d2 = "2014-03-17"; echo (int)abs((strtotime($d1) - strtotime($d2))/(60*60*24*30));
http://www.tricksofit.com/2013/12/calculate-the-difference-between-two-dates-in-php
答案 1 :(得分:0)
// @link http://www.php.net/manual/en/class.datetime.php
$d1 = new DateTime(date('Y-m-d'));
$d2 = new DateTime(MyObject->getDate());
// @link http://www.php.net/manual/en/class.dateinterval.php
$interval = $d2->diff($d1);
$interval->format('%m months');
答案 2 :(得分:0)
DateTime::diff
返回相对值,但days
除外。
因此,要计算月份的绝对差异,您必须使用:
$datetime1->diff($datetime2)->format('%y')*12+$datetime1->diff($datetime2)->format('%m');
答案 3 :(得分:0)
$currentDateTime = new DateTime;
$dateTimeInTheFuture = new DateTime(MyObject->getDate());
$dateInterval = $dateTimeInTheFuture->diff($currentDateTime);
$totalMonths = 12 * $dateInterval->y + $dateInterval->m;
echo $totalMonths;
答案 4 :(得分:0)
您只是错过单引号终止,
$datetime1 = new DateTime(date('Y-m-d'));
$datetime2 = new DateTime(MyObject->getDate());
echo($datetime1->format('d/m/Y'));
echo($datetime2->format('d/m/Y'));//You are missing single quote here
我也尝试使用此代码,
<?php
$datetime1 = date_create('2009-10-11');
$datetime2 = date_create('2009-12-13');
echo($datetime1->format('d/m/Y'));
echo "<br/>";
echo($datetime2->format('d/m/Y'));
$dateInterval = $datetime1->diff($datetime2);
//print_r(arrayColumn($dateInterval,'m'));
echo "<br>Month are :".$dateInterval->format('%m');
exit;
?>