使用 DateTime 类计算日期差异时出错
我正在尝试使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
二月不是有28天吗?由于某种原因,它可能会选择二月作为“月”单位。该方法的 PHP 文档似乎表明这种情况很容易发生。无论如何,说“x 个月”并不太有用,因为一个月不是固定单位,可能是 28、29、30 或 31 天。
摘自下面的 PHP dateinterval 格式文档。
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.