I needed a PHP code that calculates how many days have passed between today and another date in the past.
There are several ways to achieve this. Here is one of them:
PHP-only version
$first_date = '2023-01-01';
$today = date( 'Y-m-d' );
// Convert the dates to Unix timestamps and calculate the difference.
$date_diff = strtotime( $today ) - strtotime( $first_date );
$number_of_days = round( $date_diff / 86400 );
WordPress version
If this is a WordPress site, there are few optimizations we can make to this code:
Replacing
date( 'Y-m-d' )
withcurrent_time( 'Y-m-d' )
to use the built-in function of WordPress for retrieving the current date based on the site’s time zone. A secondtrue
parameter can be passed to get the time in GMT.Replacing
86400
(the number of seconds in a day =(60 * 60 * 24)
) withDAY_IN_SECONDS
- a built-in WordPress constant - to make the code more readable and clear.
That is:
$first_date = '2023-01-01';
$today = current_time( 'Y-m-d' );
// Convert the dates to Unix timestamps and calculate the difference.
$date_diff = strtotime( $today ) - strtotime( $first_date );
$number_of_days = round( $date_diff / DAY_IN_SECONDS );