为什么这个DateTime用法没有正确地说明“今天”?

时间:2017-11-19 16:36:42

标签: php datetime

为什么使用DateTime无法正确判断“classtime是否为今天”? 2017-11-19的结果是“上课时间已经过去了”。我是否需要从php.ini中引用时区?

$class = new DateTime('2017-11-19'); 
$today = new DateTime('NOW'); 
if ($class > $today) {
    echo 'classtime is in the future', PHP_EOL;
} elseif ($class < $today) {
    echo 'classtime is in the past', PHP_EOL;
} else {
    echo 'classtime is today', PHP_EOL;
}

与此相同的结果:

$class = new DateTime('2017-11-18'); 
$today = new DateTime('NOW'); 

$class->format('Y-m-d') < $today->format('Y-m-d');

if ($class > $today) {
    echo 'classtime is in the future', PHP_EOL;
} elseif ($class < $today) {
    echo 'classtime is in the past', PHP_EOL;
} else {
    echo 'classtime is today', PHP_EOL;
}

1 个答案:

答案 0 :(得分:3)

DateTime也使用时间。所以$class 2017-11-19 00:00:00 $today$class->format('Y-m-d') < $today->format('Y-m-d'); 稍晚一点,当地时间是小时等等......

有关详细信息,另请参阅示例区域中的http://php.net/manual/en/datetime.construct.php

可能你必须这样检查:

$class = new DateTime('2017-11-19');
$today = new DateTime('NOW');

$class_date = $class->format('Y-m-d');
$today_date = $today->format('Y-m-d');

if ($class_date > $today_date) {
    echo 'classtime is in the future', PHP_EOL;
} elseif ($class_date < $today_date) {
    echo 'classtime is in the past', PHP_EOL;
} else {
    echo 'classtime is today', PHP_EOL;
}

使用它像:

    Rectangle envelope = new Rectangle(216, 14400);//margenes

    Document doc = new Document(envelope, 0, 0, 0, 0);