Skip to content

Instantly share code, notes, and snippets.

@hakre
Created April 16, 2012 09:06
Show Gist options
  • Save hakre/2397187 to your computer and use it in GitHub Desktop.
Save hakre/2397187 to your computer and use it in GitHub Desktop.
Contextual user-friendly time and dates with PHP
<?php
/**
* @link http://snipt.net/pkarl/pkarlcom-contextualtime/
* @link http://pkarl.com/articles/contextual-user-friendly-time-and-dates-php/
*/
function contextualTime($small_ts, $large_ts=false) {
if(!$large_ts) $large_ts = time();
$n = $large_ts - $small_ts;
if($n <= 1) return 'less than 1 second ago';
if($n < (60)) return $n . ' seconds ago';
if($n < (60*60)) { $minutes = round($n/60); return 'about ' . $minutes . ' minute' . ($minutes > 1 ? 's' : '') . ' ago'; }
if($n < (60*60*16)) { $hours = round($n/(60*60)); return 'about ' . $hours . ' hour' . ($hours > 1 ? 's' : '') . ' ago'; }
if($n < (time() - strtotime('yesterday'))) return 'yesterday';
if($n < (60*60*24)) { $hours = round($n/(60*60)); return 'about ' . $hours . ' hour' . ($hours > 1 ? 's' : '') . ' ago'; }
if($n < (60*60*24*6.5)) return 'about ' . round($n/(60*60*24)) . ' days ago';
if($n < (time() - strtotime('last week'))) return 'last week';
if(round($n/(60*60*24*7)) == 1) return 'about a week ago';
if($n < (60*60*24*7*3.5)) return 'about ' . round($n/(60*60*24*7)) . ' weeks ago';
if($n < (time() - strtotime('last month'))) return 'last month';
if(round($n/(60*60*24*7*4)) == 1) return 'about a month ago';
if($n < (60*60*24*7*4*11.5)) return 'about ' . round($n/(60*60*24*7*4)) . ' months ago';
if($n < (time() - strtotime('last year'))) return 'last year';
if(round($n/(60*60*24*7*52)) == 1) return 'about a year ago';
if($n >= (60*60*24*7*4*12)) return 'about ' . round($n/(60*60*24*7*52)) . ' years ago';
return false;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment