Friday, 3 June 2016

PHP function to check date or time between the given range

Simply use strtotime php function to solve the problem.

strtotime — "The function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp"
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 2012-12-31 and 2013-11-26.

if(check_date_is_within_range('2012-12-31', '2013-11-26', date("Y-m-d"))){
    echo 'In range';
} else {
    echo 'Not in range';
}

0 comments:

Post a Comment