Last active
August 29, 2015 14:02
-
-
Save chrisveness/4d45842153cddf41ae60 to your computer and use it in GitHub Desktop.
Describe how long ago something happened in the past
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Returns how long ago something happened in the past, showing it as | |
* 'n' seconds / minutes / hours / days / weeks / months / years ago. | |
* | |
* For periods over a day, it rolls over at midnight (so doesn't depend on | |
* current time of day), and it correctly accounts for month-lengths and | |
* leap-years (months and years rollover on current day of month). | |
* | |
* $param string $timestamp Timestamp of past event in DateTime format. | |
* $return string Description of interval since timestamp. | |
*/ | |
function ago($timestamp) | |
{ | |
$then = date_create($timestamp); | |
// for anything over 1 day, make it rollover on midnight | |
$today = date_create('tomorrow'); // ie end of today | |
$diff = date_diff($then, $today); | |
if ($diff->y > 0) return $diff->y.' year'.($diff->y>1?'s':'').' ago'; | |
if ($diff->m > 0) return $diff->m.' month'.($diff->m>1?'s':'').' ago'; | |
$diffW = floor($diff->d / 7); | |
if ($diffW > 0) return $diffW.' week'.($diffW>1?'s':'').' ago'; | |
if ($diff->d > 1) return $diff->d.' day'.($diff->d>1?'s':'').' ago'; | |
// for anything less than 1 day, base it off 'now' | |
$now = date_create(); | |
$diff = date_diff($then, $now); | |
if ($diff->d > 0) return 'yesterday'; | |
if ($diff->h > 0) return $diff->h.' hour'.($diff->h>1?'s':'').' ago'; | |
if ($diff->i > 0) return $diff->i.' minute'.($diff->i>1?'s':'').' ago'; | |
return $diff->s.' second'.($diff->s==1?'':'s').' ago'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment