Skip to content
Advertisement

PHP find the days until a date

I have to find the number of days until a date in timestamp format (mysql db)

$row['date_exp'] format is '2013-12-16 10:00:00';
$datenow = date("Y-m-d");
$diff = (strtotime($row['date_exp']) - strtotime($datenow))/(86400);
$days = sprintf("%02d", $diff);

My problem is that if date now is 2013-12-01 09:59:00 the days are 15 while datenow is 2013-12-01 10:01:00 the days are 14.

How could I make a difference only of the days without the time?

Advertisement

Answer

Using the DateTime class:

$a = new DateTime('now');
$b = new DateTime('2013-12-16');

$a->diff($b);

returns

DateInterval Object
(
    [y] => 0
    [m] => 1
    [d] => 24
    [h] => 8
    [i] => 3
    [s] => 23
    [invert] => 0
    [days] => 54  // This is what you're looking for?
)
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement