How to Determine if a Date Falls Within a Defined Range
In programming, you may encounter the task of checking whether a user-provided date falls within a predetermined date range. This can be crucial for scenarios like validating user input or filtering data based on temporal criteria.
Converting to Timestamps for Efficient Comparison
To tackle this task effectively, it's advisable to convert the dates to timestamps using the strtotime function. This will transform the strings representing dates into numerical representations (epoch timestamps) representing the number of seconds since January 1, 1970.
Establishing a Range Check Function
With the dates converted to timestamps, you can create a function to perform the range check:
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)); }
This function takes three timestamp parameters: the start date, end date, and the date to check. It employs a logical comparison to determine if the user-provided date falls within the specified range and returns a boolean value accordingly.
Sample Usage
To utilize this function, simply pass in the relevant dates as timestamp parameters:
check_in_range('2009-06-17', '2009-09-05', '2009-08-28');
This usage example will check if '2009-08-28' falls within the range defined by '2009-06-17' and '2009-09-05', returning true if it does and false if it doesn't.
The above is the detailed content of How to Check if a Date Lies Within a Specific Range?. For more information, please follow other related articles on the PHP Chinese website!