如何检查我们是否在PHP的每周时间窗口内?

时间:2013-07-17 23:55:23

标签: php date time window

我需要每周在特定时间窗口中运行代码,并且如果我们在窗口之外,则运行等效代码。它需要智能夏令时。

窗口是每周四19:55到21:05都柏林时区时间,如果在该时间段内运行functionX(),则运行functionY()。

date_default_timezone_set("Europe/Dublin");
$currentDay = date("N");
$currentTime = date("H:i"); 

if (($currentDay == 4) && (($currentTime >= strtotime("19:55:00") ) && ($currentTime <= strtotime("21:05:00") ) ) ) {
    functionX();
} else {
    functionY();
}

我是否正确地使用了这个,并且有更好的方法来做这个逻辑吗?

2 个答案:

答案 0 :(得分:0)

哦,在括号问题旁边,您要将 $ currentTime (常规字符串,date)与整数进行比较(Unix时间戳,strtotime) 。您可能希望$ currentTime也是Unix时间戳整数。尝试使用

$currentTime = strtotime("now")

完整代码:

$currentDay = date("N");
$currentTime = strtotime("now");

if ( ($currentDay == 4) && ($currentTime >= strtotime("19:55:00")) && ($currentTime <= strtotime("21:05:00")) ) {
    functionX();
} else {
    functionY();
}

答案 1 :(得分:0)

$schedToday = '11am-5pm';

isBusinessOpen($daytoday]);

function isBusinessOpen($time_str){
    //Get the position of the dash so that you could get the start and closing time
    $cut = strpos($time_str, '-');
    
    //use substring to get the first windows time and use strtotime to convert it to    
    $opening_time = strtotime(substr($time_str, 0, $cut));
    
    //same as the first but this time you need to get the closing time  
    $closing_time = strtotime(substr($time_str, $cut + 1));
    
    //now check ifthe closing time is morning so that you could adjust the date since most likely an AM close time is dated tomorrow
    if(strpos(strtolower(substr($time_str, $cut + 1)), 'am')){
        $closing_time = strtotime(date('m/d/y') . ' ' . substr($time_str, $cut + 1) . ' + 1 day');
        $opening_time = strtotime(date('m/d/y') . ' ' . substr($time_str, 0, $cut));
    }
    //to get the current time. take note that this will base on your server time
    $now = strtotime('now');    

    // now simply check if the current time is > than opening time and less than the closing time
    return $now >= $opening_time && $now < $closing_time;
}