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??
Asked
Active
Viewed 2.5k times
2 Answers
7
Simply use strtotime to convert the two times into unix timestamps:
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
}

Hamish
- 22,860
- 8
- 53
- 67
-
1+1 but I would expect the logic to use >= and <= so that the range is inclusive – Paul Dixon Nov 16 '10 at 07:53
6
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.
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';
}

PiggyMacPigPig
- 345
- 4
- 10