简体   繁体   English

PHP - DateTime diff()显示两个日期的0个月,一年差异?

[英]PHP - DateTime diff() shows 0 months for two dates with one year difference?

I was running a quick test to help a co-worker with a problem related to dates in PHP using the DateTime object. 我正在运行一个快速测试,以帮助同事使用DateTime对象解决与PHP中的DateTime相关的问题。

Surprisingly, when I run this piece of code: 令人惊讶的是,当我运行这段代码时:

namespace Tests\DateTime {
    $date1 = new \DateTime("2013-01-01", new \DateTimeZone("UTC"));
    $date2 = new \DateTime("2014-01-01", new \DateTimeZone("UTC"));
    $interval = $date1->diff($date2);
    print $interval->m;
}

I get 0 as the return value. 我得到0作为返回值。 When you use it to measure the different between those two dates within the same year, everything works fine. 当你用它来测量同一年内这两个日期之间的差异时,一切正常。 1,2,3,4,5, ..., 11 months difference from January to December. 1,2,3,4,5, ..., 11从1月到12月有1,2,3,4,5, ..., 11个月的差异。

Why is it happening? 为什么会这样?

I think you're getting zero because you're only printing the difference in months. 我认为你是零,因为你只打印了几个月的差异。 You likely want to run your interval through DateInterval::format . 您可能希望通过DateInterval :: format运行您的间隔。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM