使用DateTime类计算日期差异时出错 [英] Error to calculate date diff with DateTime class

查看:82
本文介绍了使用DateTime类计算日期差异时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用DateTime类(php> = 5.3)来计算2个日期之间的差。

i'm trying to use the class DateTime (php>=5.3) to calculate difference from 2 date.

手册中的示例非常简单明了,我尝试了那个例子,并表现良好。
但如果更改开始日期和结束日期,则会出现问题:

The example from the manual is simple and clear, i tried that example and work good. But if a change the start and end date, there a problem:

        $this->start_date = '2011-03-01';
        $this->end_date = '2011-03-31';

        var_dump($this->start_date, $this->end_date);

        $datetime1 = new DateTime($this->start_date);
        $datetime2 = new DateTime($this->end_date);

        $interval = $datetime2->diff($datetime1);

        echo $interval->format('%a total days')."\n";
        echo $interval->format('%m month, %d days');

输出为:

30 total days     //ok
1 month, 2 days   //no! i think it should be 0 month, 30 days

随着游行进行得不是很好! :)

With march don't work very well! :)

推荐答案

二月有28天吗?出于某种原因,它可能选择2月作为月单位。该方法的PHP文档似乎暗示这种情况很容易发生。反之,说 x个月并不是太有用,因为一个月不是固定单位,可能是28、29、30或31天。

Aren't there 28 days in February? It might be picking February for the "month" unit for some reason or other. The PHP documentation for the method seems to suggest this kind of thing could easily be the case. Saying "x Months" isn't overly useful anyway as a month isn't a fixed unit, it could be 28, 29, 30 or 31 days.

下面的 PHP dateinterval格式文档


DateInterval :: format()方法不会
重新计算
时间字符串或日期段中的结转点。
这是预料之中的,因为
不可能溢出 32
days之类的值,这可以解释为
从 1个月零4天到$ b $的任何值b 1个月零1天。

The DateInterval::format() method does not recalculate carry over points in time strings nor in date segments. This is expected because it is not possible to overflow values like "32 days" which could be interpreted as anything from "1 month and 4 days" to "1 month and 1 day".

这篇关于使用DateTime类计算日期差异时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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