比较当前时间如果是午夜时间

时间:2014-01-04 08:24:09

标签: php

我长期以来一直坚持这个问题。我的任务是设置一个crontab来自动关闭服务器" EVERYDAY"用于维护。但是,如果"结束"时间是那天的午夜,我不知道如何验证比较。这里有一些例子:

// if i want to stop the server from 20:00 and to start it at 23:00, i would code like this
$current_time = date('Gi'); // for example: 1730
$start_time = 2000;
$end_time = 2300;
if ( $current_time >= $start_time && $current_time <= $end_time ){
    echo "Server is close"; // simple to compare
}
else {
    echo "Server is open"; // simple to compare
}

我知道每个人都很简单,但是,如果我希望在20:00到01:00之间关闭它,我就会坚持下去

$current_time = date('Gi'); // for example: 2130
$start_time = 2000;
$end_time = 0100;

如果它跨过午夜,我如何设置if..else比较的时间? 谢谢你的帮助......

1 个答案:

答案 0 :(得分:0)

试试这个:

$start_time = 1200;
$end_time = 2300;

if ($end_time < $start_time) {
    $end_time_2 = strtotime(date('c',format_time($start_time)) . " +1 day");
} else {
    $end_time_2 = format_time($end_time);
}

if ( time() >= format_time($start_time) && time() <= $end_time_2 ){
    echo "Server is close";
}
else {
    echo "Server is open";
}

function format_time($time) {
    return strtotime(date('Y-m-d ').floor($time / 100).':'.($time % 100));
}