Skip to content
Advertisement

Increment variable date in PHP

I am grabbing the post published date (WordPress) and trying to add 2 days to it to create a post expiry date. But I am throwing the following error:

Notice: A non well formed numeric value encountered

Here is my code:

$published_date = get_the_date( 'd/m/Y', get_the_ID() );
echo 'Pub: ' . $published_date . '<br />';  
        
$expiry_date = date( 'd/m/Y', strtotime( $published_date, '+2 days' ) );
echo 'Exp: ' . $expiry_date . '<br />';

Can anyone point out my error here please?

Advertisement

Answer

When using slashes to separate your date parts PHP assume month/day/year format. You are using day/month/year format which can result in dates that not possible (i.e. 30/12/2021).

When manipulating date values either use Unix timestamps or month/day/year format:

$published_date = get_the_date( 'm/d/Y', get_the_ID() );
echo 'Pub: ' . $published_date . '<br />';  
        
$expiry_date = date( 'd/m/Y', strtotime( $published_date, '+2 days' ) );
echo 'Exp: ' . $expiry_date . '<br />';
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement