PHP条件日期处理 - 比较时间和&日期

时间:2017-01-19 09:34:48

标签: php

我想为我的功能提供条件。这是逻辑。

预订截止日期为今天12点。 如果当前时间在关闭时间之前(例如今天上午11点),则运行函数x。我需要在预订结束时设定一个时间并将其与当前时间进行比较。

Url::to(['my_controller/action'], true);

1 个答案:

答案 0 :(得分:1)

比较DateTime对象很简单。您无需将日期时间转换为字符串。

// time when booking closes
$bookclose = new \DateTime();
$bookclose->setTimezone(new DateTimeZone('Africa/Kampala'));
$bookclose->setTime(12,0,0);

// fake a time that the booking is being made for testing
$bookingtime = new \DateTime();
$bookingtime->setTimezone(new DateTimeZone('Africa/Kampala'));

$bookingtime->setTime(11,59,59);
echo 'Booking time is ' . $bookingtime->format('d/m/Y H:i:s');
if ($bookingtime < $bookclose) {
    echo ' ALLOWED'.PHP_EOL;
} else {
    echo ' NOT ALLOWED'.PHP_EOL;
}

$bookingtime->setTime(12,0,0);
echo 'Booking time is ' . $bookingtime->format('d/m/Y H:i:s');
if ($bookingtime < $bookclose) {
    echo ' ALLOWED'.PHP_EOL;
} else {
    echo ' NOT ALLOWED'.PHP_EOL;
}

$bookingtime->setTime(12,0,1);
echo 'Booking time is ' . $bookingtime->format('d/m/Y H:i:s');
if ($bookingtime < $bookclose) {
    echo ' ALLOWED'.PHP_EOL;
} else {
    echo ' NOT ALLOWED'.PHP_EOL;
}

结果:

Booking time is 19/01/2017 11:59:59 ALLOWED
Booking time is 19/01/2017 12:00:00 NOT ALLOWED
Booking time is 19/01/2017 12:00:01 NOT ALLOWED