Question

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?

Was it helpful?

Solution

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?
)

OTHER TIPS

Just take the date component out of it.

$newDate = date("Y-m-d", strtotime($row['date_exp']));

Now this contains only the date component. You can use this to compare.

One-liner:

echo (new DateTime('2019-12-17'))->diff(new DateTime())->days; 

...returns the number of days since or until Dec 17, 2019.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top