3

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?

ashleedawg
  • 20,365
  • 9
  • 72
  • 105
Paolo Rossi
  • 2,490
  • 9
  • 43
  • 70

3 Answers3

13

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?
)
Cobra_Fast
  • 15,671
  • 8
  • 57
  • 102
2

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.

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
0

One-liner:

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

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

ashleedawg
  • 20,365
  • 9
  • 72
  • 105
  • Sure, it's not formatted to take several lines, but that's intentional since the amount of code required just to handle basic date calculations in PHP drives me *nuts.* – ashleedawg Oct 08 '19 at 11:30