如何在 PHP 5.2 中将 DateTime::diff() 与 DateTime::format('%R') 一起使用?
关于 DateTime::diff() 有很多问题(和解决方案),但我还没有找到以下代码的任何解决方案:
$start = new DateTime('13:00');
$end = new DateTime('02:00');
$difference = $start->diff($end);
if ($difference->format('%R') === '-')
{
$passedMidnight = true;
}
else
{
$passedMidnight = false;
}
这基本上就是我在 PHP 5.2 中寻找的内容:一种找出答案的方法如果 $end 与 $start 相比已经过了午夜。
There are many questions (and solutions) about DateTime::diff() around, but I haven't found any solution to the following piece of code:
$start = new DateTime('13:00');
$end = new DateTime('02:00');
$difference = $start->diff($end);
if ($difference->format('%R') === '-')
{
$passedMidnight = true;
}
else
{
$passedMidnight = false;
}
This is basically what i'm looking for in PHP 5.2: A way to find out if $end passes midnight compared to $start.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
仅仅检查两个日期是否在同一天还不够吗?
我看不出这种方法不起作用的情况,因为夏令时通常会在凌晨 2 点调整时钟(对吗?)。
Wouldn't it be enough to just check whether two dates are on the same day?
I can't see a scenario where this would not work because DST usually shifts the clocks at 2 in the morning (right?).
由于您仅使用时间构建 DateTime 对象,因此您真正想做的是查看 $end 是否早于 $start 出现。您可以使用 getTimestamp 函数来实现此目的。
Since you're constructing the DateTime objects with just times, then what you really want to do is see if $end comes earlier in the day than $start. You can use the getTimestamp function for this.
我最终做到了这一点,感谢 Pekka 和 PFHayes 的想法:
I ended up with doing this, thanks to Pekka and PFHayes for the ideas: