【问题标题】:PHP function to check time between the given range?PHP函数检查给定范围之间的时间?
【发布时间】:2010-11-16 07:00:13
【问题描述】:

我在我的项目中使用 PHP 的 Date 函数,并想检查给定日期时间是否位于给定日期时间范围之间的天气。例如,如果当前日期时间是 2010-11-16 12:25 :00 PM 并想检查时间是否在 2010-11-16 09:00:00 AM 到 06:00:00 PM 之间。在上述情况下,它是真的,如果时间不在范围之间,它应该返回假。 是否有任何内置 PHP 函数来检查这一点,否则我们将不得不编写一个新函数??

【问题讨论】:

    标签: php datetime


    【解决方案1】:

    只需使用strtotime 将两次转换为unix 时间戳:

    示例函数可能如下所示:

    function dateIsBetween($from, $to, $date = 'now') {
        $date = is_int($date) ? $date : strtotime($date); // convert non timestamps
        $from = is_int($from) ? $from : strtotime($from); // ..
        $to = is_int($to) ? $to : strtotime($to);         // ..
        return ($date > $from) && ($date < $to); // extra parens for clarity
    }
    

    【讨论】:

    • +1 但我希望逻辑使用 >= 和
    【解决方案2】:

    检查日期/时间是否在范围内的功能:

    function check_date_is_within_range($start_date, $end_date, $todays_date)
    {
    
      $start_timestamp = strtotime($start_date);
      $end_timestamp = strtotime($end_date);
      $today_timestamp = strtotime($todays_date);
    
      return (($today_timestamp >= $start_timestamp) && ($today_timestamp <= $end_timestamp));
    
    }
    

    调用函数,参数为开始日期/时间、结束日期/时间、今天的日期/时间。下面的参数获取函数来检查今天的日期/时间是否在 2012 年 6 月 26 日上午 10 点和当天中午之间。

    if(check_date_is_within_range('2012-06-26 10:00:00', '2012-06-26 12:00:00', date("Y-m-d G:i:s"))){
        echo 'In range';
    } else {
        echo 'Not in range';
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-12
      • 1970-01-01
      • 2016-10-23
      • 1970-01-01
      相关资源
      最近更新 更多