开发者

How to use DateTime::diff() with DateTime::format('%R') in PHP 5.2?

开发者 https://www.devze.com 2023-03-08 15:57 出处:网络
There are many questions (and solutions) about Dat开发者_JAVA百科eTime::diff() around, but I haven\'t found any solution to the following piece of code:

There are many questions (and solutions) about Dat开发者_JAVA百科eTime::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.


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?).


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";
}


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";
}
0

精彩评论

暂无评论...
验证码 换一张
取 消