php PHP函数检查给定范围之间的时间?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4191867/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP function to check time between the given range?
提问by Harish Kurup
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.i.e 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. In the above case its true and if the time is not in between the range it should return false. Is there any inbuild PHP function to check this or we will have to write a new function??
我在我的项目中使用 PHP 的日期函数,并想检查给定日期时间位于给定日期时间范围之间的天气。例如,如果当前日期时间是 2010-11-16 12:25:00 PM并且想检查时间是否在 2010-11-16 09:00:00 AM 到 06:00:00 PM 之间。在上述情况下,它为真,如果时间不在范围之间,则应返回假。是否有任何内置的 PHP 函数来检查这一点,否则我们将不得不编写一个新函数?
回答by Hamish
Simply use strtotimeto 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
}
回答by PiggyMacPigPig
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';
}