PHP - DateTime月差不占年差 [英] PHP - DateTime month difference not accounting for year difference

查看:116
本文介绍了PHP - DateTime月差不占年差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图将这个数字看成几个小时,但没有效果:如何在两个日期之间的整个月内获得差异,但是在一年中呢?

I've been trying to figure this one out for hours but to no avail: how does one get the difference in full months between two dates, yet accounting for year? The code below

$assignedDate = new DateTime('2011-02-03');
$firstDate = new DateTime('2013-03-03');
$interval = $assignedDate->diff($firstDate);
$months = (int)$interval->format('%m');

坚信两者之间的差异是1,但是这不适用于我的应用程序和49将是预期的结果,我已经调查并发现这个代码从这个美好的地方,但得到错误的字符串连接操作符,所以我假设问题在于他们的输出和put(int) ,但是得到0:

Is in the strong belief that the difference between the two is 1, however, this is not applicable for my application and 49 would be the expected result, I've investigated and found this code from this wonderful place but get "Wrong string concatenation operator", so I assumed the problem lay with their stringy output and put (int) ahead of the two, but got 0:

echo (($diff->format('%y') * 12) + $diff->format('%m')) . " full months difference";

是否有一个可靠的解决方案来查找年度的两个日期之间的月差? >

Is there a reliable solution to finding the month difference between two dates accounting for the year?

推荐答案

不需要使用 format()方法格式化数字。您只需访问 DateInterval 对象:

No need to format numbers with format() method. You can simply access public properties on DateInterval object:

$months = $interval->m + $interval->y * 12;

demo

这篇关于PHP - DateTime月差不占年差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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