问题描述
|
关于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中寻找的东西:一种与$ start相比,找出$ end是否在午夜过去的方法。
解决方法
仅检查两个日期是否在同一天就足够了吗?
$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\";
我看不到这种情况不起作用的情况,因为DST通常将时钟在凌晨2点移动(对吗?)。
, 由于您仅用时间构造DateTime对象,因此您真正想做的就是查看$ end是否比$ start早到。您可以为此使用getTimestamp函数。
if ($end->getTimestamp() < $start->getTimestamp()) {
echo \"Midnight has passed\";
} else {
echo \"Midnight has not passed\";
}
, 由于Pekka和PFHayes的想法,我最终做到了这一点:
$start = strtotime(\'13:00\');
$end = strtotime(\'01:00\');
if ($end < $start)
{
echo \"Midnight has passed\";
}
else
{
echo \"Midnight has not passed\";
}