PHP字符串格式的日期时间操作

PHP字符串格式的日期时间操作

问题描述:

I have several shops in my system. Now i online want to show shops that are open or will open if the nowtime is before the closing time. the time strings I use are 24 hour format like "01:00" and "23:22" I came up with a code like this:

    public function willOpen($open, $closed, $nowTime) {
    $open = str_replace(":", "", $open);
    $closed = str_replace(":", "", $closed);
    $nowTime = str_replace(":", "", $nowTime);
    if ($open >= $nowTime) {
        if ($closed <= $nowTime) {
            return false;
        } else {
            return true;
        }
    }
    return false;
}

But this does not seem right because if the close time is for ex. 01:00 and the current time is 9:00 and the shop will open for ex 11:00 then this code will return false because the close time is smaler then the now time.....

what is the best approach do to this ?

我的系统中有几家商店。 现在我在线想要展示开放的商店,或者如果现在时间在关闭时间之前将开放。 我使用的时间字符串是24小时格式,如“01:00”和“23:22”我想出了这样的代码: p>

  public function willOpen($ open  ,$ closed,$ nowTime){
 $ open = str_replace(“:”,“”,$ open); 
 $ closed = str_replace(“:”,“”,$ closed); 
 $ nowTime = str_replace  (“:”,“”,$ nowTime); 
 if($ open&gt; = $ nowTime){
 if($ closed&lt; = $ nowTime){
 return false; 
} else {
 返回true; 
} 
} 
返回false; 
} 
  code>  pre> 
 
 

但这似乎不对,因为如果关闭时间是ex。 01:00和当前时间是9:00,商店将在11:00开放,然后这段代码将返回false,因为关闭时间比现在更短..... p>

最好的办法是什么? p> div>

The best way to go is using DateTime classes, as time operations is supported. So it's would be something like this:

function willOpen(Datetime $open, Datetime $closed)
{
    $nowTime = new DateTime(); # defaults to now 

    // if ($nowTime > $closed) ...
}

$open   = Datetime::createFromFormat('H:i', '01:00');
$closed = Datetime::createFromFormat('H:i', '09:00');

If closed is the next day so you could a bit like:

$closed->add(new DateInterval('P1DT12H')); # 1 day + 12 hours

I would cast all of the dates to unix time and compare from that. It's much more accurate and designed for this sort of thing. date("U") is the unix time since epoc (and is an integer), so comparing > and < on it is a breeze.

$open = date("U",strtotime($open));
$closed = date("U",strtotime($closed));
$nowTime = date("U");
if ($open >= $nowTime) {
 if ($closed <= $nowTime) {
  return false;
 }
 else {
  return true;
 }
}
return false;