使用 DateTime 类计算日期差异时出错

发布于 2024-10-21 01:03:03 字数 733 浏览 0 评论 0原文

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

手册中的示例简单明了,我尝试了该示例并且效果很好。 但如果更改开始和结束日期,则会出现问题:

        $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! :)

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

Output is:

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! :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦魇绽荼蘼 2024-10-28 01:03:03

二月不是有28天吗?由于某种原因,它可能会选择二月作为“月”单位。该方法的 PHP 文档似乎表明这种情况很容易发生。无论如何,说“x 个月”并不太有用,因为一个月不是固定单位,可能是 28、29、30 或 31 天。

摘自下面的 PHP dateinterval 格式文档

DateInterval::format() 方法确实
不重新计算结转点
时间字符串也不在日期段中。
这是预期的,因为它不是
可能会溢出诸如“32
天”,可以解释为
从“1 个月零 4 天”到
“1个月又1天”。

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.

Extract from the PHP dateinterval format documentation below.

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".

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文