Home >Backend Development >PHP Tutorial >How Can I Compare a Given Date with Today's Date in PHP?
Comparing a Given Date with Today
Given a date stored in a variable, such as $var = "2010-01-21 00:00:00.0", it is often necessary to compare it with today's date to determine its relative position in time. To accomplish this, several built-in PHP functions can be employed.
Solution:
The following steps outline the approach for comparing $var with today's date:
Convert the String to Time Value:
Use the strtotime() function to convert $var into a UNIX timestamp representing the number of seconds since January 1, 1970.
$timestamp = strtotime($var);
Calculate the Time Difference:
Subtract the UNIX timestamp of $var from the current time, which can be obtained using the time() function.
$timeDiff = time() - $timestamp;
Compare the Time Difference:
Determine the relative position of $var compared to today's date:
For instance, the following code snippet demonstrates how to check if $var has occurred within the last day:
if (($timeDiff / (60 * 60 * 24)) < 1) { ... }
The above is the detailed content of How Can I Compare a Given Date with Today's Date in PHP?. For more information, please follow other related articles on the PHP Chinese website!