Skip to content

Instantly share code, notes, and snippets.

@kopiro
Created July 26, 2012 21:06
Show Gist options
  • Save kopiro/3184515 to your computer and use it in GitHub Desktop.
Save kopiro/3184515 to your computer and use it in GitHub Desktop.
Time ago function PHP
<?php
function time_ago($date, $granularity=1)
{
$date = strtotime($date);
if (!$date) return '';
$difference = time() - $date;
$periods = array(
'decad' => 315360000,
'ann' => 31536000,
'mes' => 2628000,
'settiman' => 604800,
'giorn' => 86400,
'or' => 3600,
'minut' => 60,
'second' => 1);
if ($difference < 5)
{
return "proprio ora";
}
else
{
foreach ($periods as $key => $value)
{
if ($difference >= $value) {
$time = floor($difference/$value);
$difference %= $value;
$retval .= ($retval ? ' ' : '').$time.' ';
$retval .= $key;
if ($time>1)
{
if (in_array($key, array('or','settiman'))) $retval .= 'e';
else $retval .= 'i';
}
else
{
if (in_array($key, array('second','minut','giorn'))) $retval .= 'o';
else if (in_array($key, array('or','settiman'))) $retval .= 'a';
else $retval .= 'e';
}
$granularity--;
}
if ($granularity == '0') { break; }
}
return $retval.' fa';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment