如何在 PHP 5.2 中将 DateTime::diff() 与 DateTime::format('%R') 一起使用?

发布于 2024-11-10 02:52:06 字数 366 浏览 1 评论 0原文

关于 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 技术交流群。

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

发布评论

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

评论(3

等风也等你 2024-11-17 02:52:06

仅仅检查两个日期是否在同一天还不够吗?

$start = new DateTime('13:00');
$end = new DateTime('02:00');

if ($start->format('Y-m-d') == $end->format('Y-m-d'))
 echo "Midnight has NOT passed";
else
 echo "Midnight has passed";

我看不出这种方法不起作用的情况,因为夏令时通常会在凌晨 2 点调整时钟(对吗?)。

Wouldn't it be enough to just check whether two dates are on the same day?

$start = new DateTime('13:00');
$end = new DateTime('02:00');

if ($start->format('Y-m-d') == $end->format('Y-m-d'))
 echo "Midnight has NOT passed";
else
 echo "Midnight has passed";

I can't see a scenario where this would not work because DST usually shifts the clocks at 2 in the morning (right?).

再浓的妆也掩不了殇 2024-11-17 02:52:06

由于您仅使用时间构建 DateTime 对象,因此您真正想做的是查看 $end 是否早于 $start 出现。您可以使用 getTimestamp 函数来实现此目的。

if ($end->getTimestamp() < $start->getTimestamp()) {
    echo "Midnight has passed";
} else {
    echo "Midnight has not passed";
}

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.

if ($end->getTimestamp() < $start->getTimestamp()) {
    echo "Midnight has passed";
} else {
    echo "Midnight has not passed";
}
∞觅青森が 2024-11-17 02:52:06

我最终做到了这一点,感谢 Pekka 和 PFHayes 的想法:

$start = strtotime('13:00');
$end = strtotime('01:00');

if ($end < $start)
{
    echo "Midnight has passed";
}
else
{
    echo "Midnight has not passed";
}

I ended up with doing this, thanks to Pekka and PFHayes for the ideas:

$start = strtotime('13:00');
$end = strtotime('01:00');

if ($end < $start)
{
    echo "Midnight has passed";
}
else
{
    echo "Midnight has not passed";
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文