Home >Backend Development >PHP Tutorial >How Can I Check if a Date Is Within a Given Range?

How Can I Check if a Date Is Within a Given Range?

Susan Sarandon
Susan SarandonOriginal
2024-12-01 09:20:13618browse

How Can I Check if a Date Is Within a Given Range?

Determining If a Date Falls within a Specified Range

Given a starting and ending date, how can you verify if a user-specified date lies within that range?

Example:

$start_date = '2009-06-17';
$end_date = '2009-09-05';
$date_from_user = '2009-08-28';

Converting to Timestamps

To facilitate this validation, it's beneficial to convert the dates to timestamp integers using the strtotime function.

Implementation:

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

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

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

Explanation:

This code snippet converts the given dates to timestamps. The check_in_range function then compares the user-specified date against the start and end timestamps. If the user date is greater than or equal to the start timestamp and less than or equal to the end timestamp, the function returns true, indicating that the date falls within the range. Otherwise, it returns false.

The above is the detailed content of How Can I Check if a Date Is Within a Given Range?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn