Last active
December 20, 2015 00:59
-
-
Save kmaida/6045648 to your computer and use it in GitHub Desktop.
Convert a date string to UNIX timestamp and then calculate how long from now that was in the fashion of twitter.
This file contains 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
function timeAgo($dateStr) { | |
$timestamp = strtotime($dateStr); | |
$day = 60 * 60 * 24; | |
$today = time(); // current unix time | |
$since = $today - $timestamp; | |
// If it has been less than 1 day since the tweet was posted, figure out how long ago in seconds/minutes/hours | |
if (($since / $day) < 1) { | |
$timeUnits = array( | |
array(60 * 60, 'h'), | |
array(60, 'm'), | |
array(1, 's') | |
); | |
for ($i = 0, $j = count($timeUnits); $i < $j; $i++) { | |
$seconds = $timeUnits[$i][0]; | |
$unit = $timeUnits[$i][1]; | |
if (($count = floor($since / $seconds)) != 0) { | |
break; | |
} | |
} | |
return = "$count{$unit}"; | |
// If it has been a day or more, return the date: day (without leading 0) and 3-letter month | |
} else { | |
return date('j M', strtotime($dateStr)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment