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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 22:08:40  来源:igfitidea点击:

PHP Difference in months between two dates?

phpdatediff

提问by Jaiff

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

可能的重复:
如何使用 PHP 计算两个日期之间的差异?
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.

更优雅的解决方案是使用DateTimeDateInterval

<?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');

回答by Devator

Have a look at date_diff:

看看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');
?>