Skip to content

Instantly share code, notes, and snippets.

@omalave
Created February 2, 2015 16:46
Show Gist options
  • Save omalave/85d0d9608fa7bfd31553 to your computer and use it in GitHub Desktop.
Save omalave/85d0d9608fa7bfd31553 to your computer and use it in GitHub Desktop.
Time Twitter Style, moment.js in PHP
function calc_time_diff($timestamp, $unit = NULL, $show_unit = TRUE) {
$seconds = round((time() - $timestamp)); // How many seconds have elapsed
$minutes = round((time() - $timestamp) / 60); // How many minutes have elapsed
$hours = round((time() - $timestamp) / 60 / 60); // How many hours have elapsed
$days = round((time() - $timestamp) / 60 / 60 / 24); // How many hours have elapsed
$seconds_string = $seconds;
$minutes_string = $minutes;
$hours_string = $hours;
$days_string = $days;
switch($unit) {
case "seconds": return $seconds;
break;
case "minutes": return $minutes;
break;
case "hours": return $hours;
break;
case "days": return $days;
break;
default: // No time unit specified, return the most relevant
if($seconds < 60) { // Less than a minute has passed
if($seconds != 1) {
$seconds_string .= " seconds ago";
}
else {
$seconds_string .= " second ago";
}
return ($show_unit) ? $seconds_string : $seconds;
}
elseif($minutes < 60) { // Less than an hour has passed
if($minutes != 1) {
$minutes_string .= " minutes ago";
}
else {
$minutes_string .= " minute ago";
}
return ($show_unit) ? $minutes_string : $minutes;
;
}
elseif($hours < 24) { // Less than a day has passed
if($hours != 1) {
$hours_string .= " hours ago";
}
else {
$hours_string .= " hour ago";
}
return ($show_unit) ? $hours_string : $hours;
}
else { // More than a day has passed
if($days != 1) {
$days_string .= " days ago";
}
else {
$days_string .= " day ago";
}
return ($show_unit) ? $days_string : $days;
}
break;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment