计算两个日期所包含的日历月数 [英] Calculate number of calendar months that two dates encompass
问题描述
我想使用PHP或MySQL计算两个日期之间的日历月份数。
I want to calculate, using PHP or MySQL, the number of calendar months that are encompassed between two dates.
例如:
2015年2月3日(2015-02-03)和2015年4月10日(2015-04-10)将是三个月(二月,三月,四月),2015年2月28日-02-28)和2015年4月1日(2015-04-01)将是三个月(二月,三月,四月)。
February 3, 2015 (2015-02-03) and April 10, 2015 (2015-04-10) would be three months (February, March, April. Also, February 28, 2015 (2015-02-28) and April 1, 2015 (2015-04-01) would be three months (February, March, April).
所以实际的日历数几个月不重要...我只想知道一个日历上有多少个月在两个月之间。
So the actual number of calendar months don't really matter... I just want to know how many months on a calendar fall between two months.
我不能想出一个简单/
I can't come up with a simple/elegant way to do this with PHP or MySQL.
推荐答案
您可以使用这个来获得两个日期之间的总月份
You can use this to get total months between two dates
$date1 = '2015-10-25';
$date2 = '2016-07-20';
$year1 = date('Y', strtotime($date1));
$year2 = date('Y', strtotime($date2));
$month1 = date('m', strtotime($date1));
$month2 = date('m', strtotime($date2));
$diff = (($year2 - $year1) * 12) + ($month2 - $month1);
echo $diff;
希望这有帮助。谢谢。
这篇关于计算两个日期所包含的日历月数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!