简体   繁体   English

PHP函数检查给定范围之间的时间?

[英]PHP function to check time between the given range?

I am using PHP's Date functions in my project and want to check weather a given date-time lies between the given range of date-time.ie for example if the current date-time is 2010-11-16 12:25:00 PM and want to check if the time is between 2010-11-16 09:00:00 AM to 06:00:00 PM. 我在我的项目中使用PHP的日期函数,并希望检查天气,给定的日期时间位于date-time.ie的给定范围之间,例如,如果当前日期时间是2010-11-16 12:25:00 PM并想检查时间是否在2010-11-16 09:00:00 AM到06:00:00 PM之间。 In the above case its true and if the time is not in between the range it should return false. 在上面的情况下它是真的,如果时间不在范围之间,它应该返回false。 Is there any inbuild PHP function to check this or we will have to write a new function?? 是否有任何inbuild PHP函数来检查这个或我们将不得不写一个新函数?

Simply use strtotime to convert the two times into unix timestamps: 只需使用strtotime将两次转换为unix时间戳:

A sample function could look like: 示例函数可能如下所示:

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
}

The function to check if date/time is within the range: 检查日期/时间是否在范围内的功能:

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));

}

Call function with parameters start date/time, end date/time, today's date/time. 带参数的呼叫功能开始日期/时间,结束日期/时间,今天的日期/时间。 Below parameters gets function to check if today's date/time is between 10am on the 26th of June 2012 and noon on that same day. 以下参数可用于检查今天的日期/时间是否在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';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM