11

Possible Duplicate:
How to calculate the difference between two dates using PHP?

I have timestamps stored in the format YYYY-MM-DD HH:MM:SS (for example 2010-06-21 20:12:56). What would the best way to check how old the timestamp is? For the moment I am mainly interested in the number of days old.

Community
  • 1
  • 1
aslum
  • 11,774
  • 16
  • 49
  • 70

2 Answers2

14

You can use strtotime to convert the string to a UNIX timestamp, which is in seconds. time() will give you the current UNIX timestamp. Subtract them to get how old the date is in seconds, and divide by 60*60*24 to get it in days

It's also doable using DateTime::diff, although I find the date functions easier than using the classes

Michael Mrozek
  • 169,610
  • 28
  • 168
  • 175
  • 3
    Don't do this, you will fail miserably once DST comes into play: `` date_default_timezone_set("Europe/Amsterdam"); $d1 = strtotime("2013-10-27T00:00:00"); $d2 = strtotime("2013-10-28 00:00:00"); var_dump(($d2-$d1)/(60*60*24)); `` output: double(1.0416666666667) – Bart van den Burg Dec 10 '13 at 16:00
11
$today = strtotime(date('Y-m-d H:i:s'));
$expireDay = strtotime($row['ExpireDate']);
$timeToEnd = $expireDay - $today;
Michael Mrozek
  • 169,610
  • 28
  • 168
  • 175
Nguyen
  • 111
  • 1
  • 2