0

Hey guys, how does one calculate the days past since a date like the one Twitter outputs in its API eg:

Mon Jul 12 00:27:26 +0000 2010

to XXX

Can we do it with strtotime

Thanks guys, Dex

DexCurl
  • 1,683
  • 5
  • 26
  • 38

3 Answers3

1

Compatibility note: works only for PHP >= 5.3.0

Providing that the date format does not change, you can reverse the process (i.e. reverse timestamp -> string (on Twitters servers) to timestamp) using the exact date format. Using the table on the manual page of DateTime::createFromFormat:

<?php
$str = 'Mon Jul 12 00:27:26 +0000 2010';
$oDateTime = DateTime::createFromFormat('D M d H:i:s T Y', $str);
$unix_timestamp = $oDateTime->getTimestamp();
echo $unix_timestamp;
?>

Beware: On my machine, date('d-m-Y H:i:s', $unix_timestamp) differs two hours, the machines timezone is GMT+2.

To calculate the difference between in days between two Unix timestamps, use math (a day has 86400 seconds):

echo ($unix_timestamp1 - $unix_timestamp2) / 86400;

If you've two such dates, you can use DateTime::diff as suggested in the comments by Zerocrates. You've create two DateTime instances using DateTime::createFromFormat and invoke the DateTime::diff with two arguments passed, previously created DateTime instances. The returned DateInterval instance has a d property which contains the difference in days.
The other way would be using the getTimestamp method, doing the maths from the previous example.

References:

Lekensteyn
  • 64,486
  • 22
  • 159
  • 192
  • 1
    Since this is already creating a DateTime object, you might as well use `DateTime::diff` with the current time to get a DateInterval rather than getting the timestamp. – John Flatness May 29 '11 at 20:50
0

You might find sth here:

performing datetime related operations in PHP

or in php manual there is a lot..

http://php.net/manual/en/function.date.php

Community
  • 1
  • 1
Melsi
  • 1,462
  • 1
  • 15
  • 21
0

You can do it like that (where $your_date is the string you mentioned):

$diff = (time() - strtotime($your_date)) / (24*60*60);

In your case, when I did echo $diff; the output was (at the time I posted the answer):

321.85475694444

See more details for strtotime(), time() and date().

Hope this helped you.

Tadeck
  • 132,510
  • 28
  • 152
  • 198