How to check if a date is in a given range?

meleyal picture meleyal · Jun 10, 2009 · Viewed 138.1k times · Source

If you have a $start_date and $end_date, how can you check if a date given by the user falls within that range?

e.g.

$start_date = '2009-06-17';

$end_date = '2009-09-05';

$date_from_user = '2009-08-28'; 

At the moment the dates are strings, would it help to convert them to timestamp integers?

Answer

ConroyP picture ConroyP · Jun 10, 2009

Converting them to timestamps is the way to go alright, using strtotime, e.g.

$start_date = '2009-06-17';

$end_date = '2009-09-05';

$date_from_user = '2009-08-28';

check_in_range($start_date, $end_date, $date_from_user);


function check_in_range($start_date, $end_date, $date_from_user)
{
  // Convert to timestamp
  $start_ts = strtotime($start_date);
  $end_ts = strtotime($end_date);
  $user_ts = strtotime($date_from_user);

  // Check that user date is between start & end
  return (($user_ts >= $start_ts) && ($user_ts <= $end_ts));
}