PASSWORD RESET

Your destination for complete Tech news

PHP

How to check if a date is in past in PHP?

1.54K 0
< 1 min read

In PHP, you can check if a date is in the past by comparing it to the current date and time using the time() and strtotime() functions. Here’s an example:

$dateString = '2022-02-25'; // The date to check, in YYYY-MM-DD format
$dateTimestamp = strtotime($dateString); // Convert the date to a Unix timestamp
$currentTimestamp = time(); // Get the current Unix timestamp

if ($dateTimestamp < $currentTimestamp) {
  // The date is in the past
} else {
  // The date is in the future
}

In this example, we first convert the date string to a Unix timestamp using the strtotime() function. We then get the current Unix timestamp using the time() function. We compare the two timestamps using the < operator to check if the date is in the past. If the date is in the past, we execute the code in the first block of the if statement. Otherwise, we execute the code in the else block.

Note that this example assumes that the date is in the YYYY-MM-DD format. If your date is in a different format, you may need to use a different function to convert it to a Unix timestamp. Additionally, you may need to adjust the comparison if you want to check if the date is before or after a certain point in time, rather than checking if it is in the past.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.