Posted By

oscarduignan on 03/19/09


Tagged

time words difference


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

endorfin
kurokikaze
Nix


GetTimeDifferenceInWords


 / Published in: PHP
 

Simple function to recreate the distanceoftimeinwords function from rails.

  1. /**
  2.  * @var timestamp
  3.  * @var timestamp
  4.  * @return string approximate time, for example: about 19 hours
  5.  */
  6. function getTimeDifferenceInWords($firstTime, $secondTime = '')
  7. {
  8. // convert to unix timestamps
  9. $firstTime = strtotime($firstTime);
  10. // if second time was not supplied, use current time
  11. $secondTime = ($secondTime) ? strtotime($secondTime) : time();
  12.  
  13. // find out the difference in seconds
  14. $seconds = ($firstTime > $secondTime)
  15. ? $firstTime - $secondTime
  16. : $secondTime - $firstTime;
  17.  
  18. $minutes = floor($seconds / 60);
  19. if ($minutes == 0) { return 'less than a minute'; }
  20. if ($minutes == 1) { return 'a minute'; }
  21. if ($minutes < 45) { return $minutes . ' minutes'; }
  22.  
  23. $hours = round($minutes / 60);
  24. if ($hours <= 1) { return 'about 1 hour'; }
  25. if ($hours < 24) { return 'about ' . $hours . ' hours'; }
  26.  
  27. $days = round($hours / 24);
  28. if ($days == 1) { return 'about 1 day'; }
  29. if ($days < 30) { return 'about ' . $days . ' days'; }
  30.  
  31. $months = round($days / 30);
  32. if ($months == 1) { return 'about 1 month'; }
  33. if ($months < 12) { return 'about ' . $months . ' months'; }
  34.  
  35. $years = round($months / 12);
  36. if ($years == 1) { return 'about 1 year'; }
  37. return 'about ' . $years . ' years';
  38. }

Report this snippet  

You need to login to post a comment.