PHP Difference in months between two dates? [duplicate]

倖福魔咒の 提交于 2019-12-18 05:43:43

问题


Possible Duplicate:
How to calculate the difference between two dates using PHP?
Date Difference in php?

I have two dates in a variable like

$fdate = "2011-09-01"

$ldate = "2012-06-06"

Now I need the difference in months between them.
For example, the answer should be 10 if you calculate this from month 09 (September) to 06 (June) of next year - you'll get 10 as result.
How can I do this in PHP?


回答1:


A more elegant solution is to use DateTime and DateInterval.

<?php

// @link http://www.php.net/manual/en/class.datetime.php
$d1 = new DateTime('2011-09-01');
$d2 = new DateTime('2012-06-06');

// @link http://www.php.net/manual/en/class.dateinterval.php
$interval = $d2->diff($d1);

$interval->format('%m months');



回答2:


Have a look at date_diff:

<?php
$datetime1 = date_create('2009-10-11');
$datetime2 = date_create('2009-10-13');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%m months');
?>


来源:https://stackoverflow.com/questions/10427694/php-difference-in-months-between-two-dates

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!