如何在PHP中比较两次

Raj*_*kar 16 php datetime

我曾在格式两次一样7点三十分00秒和22点30分〇 〇秒存储在变量$resttimefrom$resttimeto分别.

我想检查当前时间是否在这两个值之间.我正在检查这个代码

$time = date("G:i:s");
if ($time > $resttimefrom and $time < $resttimeto ){
    $stat = "open";
} else {
    $stat = "close";
} 
Run Code Online (Sandbox Code Playgroud)

但我总是把$ stat作为Close.可能导致什么?

Alf*_*wed 22

一种简单而智能的方法是从日期中删除":".

$resttimefrom = 73000;
$resttimeto = 223000;

$currentTime = (int) date('Gis');

if ($currentTime > $resttimefrom && $currentTime < $resttimeto )
{
    $stat="open";
}
else
{
    $stat="close";
} 
Run Code Online (Sandbox Code Playgroud)


Zub*_*rya 22

你可以尝试使用 strtotime

$st_time    =   strtotime($resttimefrom);
$end_time   =   strtotime($resttimeto);
$cur_time   =   strtotime(now);
Run Code Online (Sandbox Code Playgroud)

然后检查

if($st_time < $cur_time && $end_time > $cur_time)
{
   echo "WE ARE CLOSE NOW !!";
}
else{
   echo "WE ARE OPEN  NOW !!";
}
Run Code Online (Sandbox Code Playgroud)

我希望这可以帮助你..

  • +1帮助但避免错误"注意:现在使用未定义的常量 - 假设'现在'",将关键字封装到引号中 (2认同)

Raj*_*kar -6

正如 Shrapnel 上校所说,我正在将所有时间转换为秒,然后将其与当前时间的总秒数进行比较