PHP 两个日期之间的月数差异?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10427694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP Difference in months between two dates?
提问by Jaiff
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?
现在我需要它们之间的月差。
例如,如果您从明年 09 月(9 月)到 06 月(6 月)计算,答案应该是 10 - 结果是 10。
我怎样才能在 PHP 中做到这一点?
回答by Boby
A more elegant solution is to use DateTimeand DateInterval.
更优雅的解决方案是使用DateTime和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');

