Home >Backend Development >PHP Tutorial >How to Check if a Date Falls Within a Given Range?

How to Check if a Date Falls Within a Given Range?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-29 09:38:10572browse

How to Check if a Date Falls Within a Given Range?

How to Determine if a Date is Within a Specified Range

In programming, it is often necessary to verify if a date falls within a specific time frame. To accomplish this, consider the following scenario:

Suppose you have three dates stored as strings: $start_date, $end_date, and $date_from_user. Your goal is to determine if $date_from_user falls within the range defined by $start_date and $end_date.

To simplify the comparison, converting these dates to timestamp integers is recommended. This can be achieved using the strtotime function.

Here's how to approach the problem:

$start_ts = strtotime($start_date);
$end_ts = strtotime($end_date);
$user_ts = strtotime($date_from_user);

if (($user_ts >= $start_ts) && ($user_ts <= $end_ts)) {
  // $date_from_user is within the range
} else {
  // $date_from_user is outside the range
}

In this example, $user_ts is compared to both $start_ts and $end_ts. If $user_ts is greater than or equal to $start_ts and less than or equal to $end_ts, it means that $date_from_user falls within the specified range.

The above is the detailed content of How to Check if a Date Falls 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