Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Human readable times in PHP
# Set a timestamp to time, e.g. 2 months
public static function time_ago($timestamp)
{
$years = floor($timestamp / 31536000);
$days = floor(($timestamp - ($years*31536000)) / 86400);
$hours = floor(($timestamp - ($years*31536000 + $days*86400)) / 3600);
$minutes = floor(($timestamp - ($years*31536000 + $days*86400 + $hours*3600)) / 60);
$timestring = '';
if ($years > 0){
$timestring .= $years . ' years ';
}
if ($days > 0) {
$timestring .= $days . ' days ';
}
if ($hours > 0) {
$timestring .= $hours . ' hrs';
}
if ($minutes > 0) {
$timestring .= $minutes . ' mins';
}
# Optional
# $timestring .= ' ago';
return $timestring;
}
# Formats a time stamp into a date string
public static function format_timestamp($timestamp, $time = false)
{
if($timestamp == 0) {
return null;
} else if(is_string($timestamp)){
$timestamp = strtotime($timestamp);
}
if ($time) {
$date_string = Date('H:i:s jS M Y', $timestamp);
} else {
$date_string = Date('jS M Y', $timestamp);
}
return $date_string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment