0

I have two variables stored in my database containing the following data:

$date_published = 2012-05-04 00:00:00; //Straight from DB datetime field
$advert_duration = 15;

I want to show an advert for 15 days from the date it was published. To do so I need to work out the time difference.

I have read various places online about calculating time difference and have come up with the below code

In my attempt to work out the equation I can't seem to calculate the differences between $now - the date today, the $date_published and the $advert_duration. I can't get the correct result:

function days_left($date_published, $advert_duration){

    $date = new DateTime($date_published);

    $now = new DateTime();

    $days_elapsed = $date->diff($now)->format("%d");

    $days_left = $advert_duration - $days_elapsed;

    return $days_left;
}
harrynortham
  • 299
  • 2
  • 4
  • 13

2 Answers2

2
function getDaysLeft( $date, $duration )
{
    // create $date and modify it by $duration
    $date = new DateTime( $date );
    $date->modify( sprintf( '+%d days', $duration ) );

    // calculate the difference
    $now = new DateTime();
    $daysElapsed = (int) $now->diff( $date )->format( '%a' );

    // set to negative value, if modified $date is before $now
    if( $date < $now )
    {
        $daysElapsed = $daysElapsed * -1;
    }
    return $daysElapsed;
}

var_dump(
    getDaysLeft( '2012-05-04 00:00:00', 15 ),
    getDaysLeft( '2012-07-04 00:00:00', 15 )
);
feeela
  • 29,399
  • 7
  • 59
  • 71
1

If you're fetching your ad from the database, you can simply use a date function to calculate this :

 WHERE DATE_SUB(CURDATE(),INTERVAL 15 DAY) >= date

Or you can do this in PHP (you'll get an UNIX timestamp) :

 $date = strtotime('+15 days', strtotime($date_published));
Ugo Méda
  • 1,205
  • 8
  • 23