使用DateInterval计算两个日期之间的月份,而不在一年内包装 [英] Calculate months between two dates using DateInterval without wrapping within a year

查看:127
本文介绍了使用DateInterval计算两个日期之间的月份,而不在一年内包装的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  $ temp_d1 = new DateTime(date( 'Ym-d',$ fromTime)); // 2012-01-01 
$ temp_d2 = new DateTime(date('Y-m-d',$ endTime)); // 2013-02-01
$ interval = $ temp_d2-> diff($ temp_d1);
$ monthsAhead = $ interval-> format('%m'); //返回1,但我期待13

如何计算两个日期之间的月份数没有包装在12个月的范围内?

解决方案

我很困惑的是:

  $ monthsAhead = $ interval-> format('%m'); 



显然,格式( '%m')只是格式化DateInterval对象的组件,不一定是给我的间隔时间。



在我的情况下,我正在寻找/执行此操作:

  $ monthsAhead = $ interval-> m +($ interval-> y * 12); 

http://www.php.net/manual/en/class.dateinterval.php



希望这个在未来帮助其他傻瓜!


I am aware this topic is pretty exhausted, but obviously not quite enough!

$temp_d1 = new DateTime(date('Y-m-d', $fromTime)); // 2012-01-01
$temp_d2 = new DateTime(date('Y-m-d', $endTime)); // 2013-02-01
$interval = $temp_d2->diff($temp_d1); 
$monthsAhead = $interval->format('%m'); // returns 1, but I am expecting 13

How do you calculate the number of months between two dates without wrapping within a 12 month scale?

解决方案

I was confusing exactly what:

$monthsAhead = $interval->format('%m');

does.

Obviously, format('%m') is just formatting the month component of the DateInterval object, not necessarily 'give me the interval as a number of months'.

In my case, I was looking for/to do this:

$monthsAhead = $interval->m + ($interval->y * 12);

http://www.php.net/manual/en/class.dateinterval.php

Hope this helps other fools in the future!

这篇关于使用DateInterval计算两个日期之间的月份,而不在一年内包装的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆