Posted By

jodm on 09/07/09


Tagged

php date twitter timespan


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

maryann
umang_nine
nb109


Timespan


 / Published in: PHP
 

Timespan like twitter "ago" time.

  1. function timespan($time1, $time2 = NULL, $output = 'years,months,weeks,days,hours,minutes,seconds')
  2. {
  3. // Array with the output formats
  4. $output = preg_split('/[^a-z]+/', strtolower((string) $output));
  5. // Invalid output
  6. if (empty($output))
  7. return FALSE;
  8. // Make the output values into keys
  9. extract(array_flip($output), EXTR_SKIP);
  10. // Default values
  11. $time1 = max(0, (int) $time1);
  12. $time2 = empty($time2) ? time() : max(0, (int) $time2);
  13. // Calculate timespan (seconds)
  14. $timespan = abs($time1 - $time2);
  15. // All values found using Google Calculator.
  16. // Years and months do not match the formula exactly, due to leap years.
  17. // Years ago, 60 * 60 * 24 * 365
  18. isset($years) and $timespan -= 31556926 * ($years = (int) floor($timespan / 31556926));
  19. // Months ago, 60 * 60 * 24 * 30
  20. isset($months) and $timespan -= 2629744 * ($months = (int) floor($timespan / 2629743.83));
  21. // Weeks ago, 60 * 60 * 24 * 7
  22. isset($weeks) and $timespan -= 604800 * ($weeks = (int) floor($timespan / 604800));
  23. // Days ago, 60 * 60 * 24
  24. isset($days) and $timespan -= 86400 * ($days = (int) floor($timespan / 86400));
  25. // Hours ago, 60 * 60
  26. isset($hours) and $timespan -= 3600 * ($hours = (int) floor($timespan / 3600));
  27. // Minutes ago, 60
  28. isset($minutes) and $timespan -= 60 * ($minutes = (int) floor($timespan / 60));
  29. // Seconds ago, 1
  30. isset($seconds) and $seconds = $timespan;
  31. // Remove the variables that cannot be accessed
  32. unset($timespan, $time1, $time2);
  33. // Deny access to these variables
  34. $deny = array_flip(array('deny', 'key', 'difference', 'output'));
  35. // Return the difference
  36. $difference = array();
  37. foreach ($output as $key)
  38. {
  39. if (isset($$key) AND ! isset($deny[$key]))
  40. {
  41. // Add requested key to the output
  42. $difference[$key] = $$key;
  43. }
  44. }
  45. // Invalid output formats string
  46. if (empty($difference))
  47. return FALSE;
  48. // If only one output format was asked, don't put it in an array
  49. if (count($difference) === 1)
  50. return current($difference);
  51. // Return array
  52. return $difference;
  53. }

Report this snippet  

You need to login to post a comment.