| 5 common.inc | format_interval($timestamp, $granularity = 2) |
| 6 common.inc | format_interval( |
| 7 common.inc | format_interval($interval, $granularity = 2, $langcode = NULL) |
| 8 common.inc | format_interval($interval, $granularity = 2, $langcode = NULL) |
Format a time interval with the requested granularity.
Parameters
$timestamp: The length of the interval in seconds.
$granularity: How many different units to display in the string.
$langcode: Optional language code to translate to a language other than what is used to display the page.
Return value
A translated string representation of the interval.
Related topics
15 calls to format_interval()
5 string references to 'format_interval'
File
- includes/
common.inc, line 1309 - Common functions that many Drupal modules will need to reference.
Code
function format_interval($timestamp, $granularity = 2, $langcode = NULL) {
$units = array(
'1 year|@count years' => 31536000,
'1 week|@count weeks' => 604800,
'1 day|@count days' => 86400,
'1 hour|@count hours' => 3600,
'1 min|@count min' => 60,
'1 sec|@count sec' => 1,
);
$output = '';
foreach ($units as $key => $value) {
$key = explode('|', $key);
if ($timestamp >= $value) {
$output .= ($output ? ' ' : '') . format_plural(floor($timestamp / $value), $key[0], $key[1], array(), $langcode);
$timestamp %= $value;
$granularity--;
}
if ($granularity == 0) {
break;
}
}
return $output ? $output : t('0 sec', array(), $langcode);
}
Login or register to post comments
Comments
this function does not have
this function does not have months as units...
months
Heres my version of an interval function that outputs [time] ago and supports months, as well as more far-away times ;)
<?php/**
* Custom date function to return [time] ago
*
*/
function ago($timestamp){
$difference = time() - $timestamp;
$periods = array('1 second', '1 minute', '1 hour', '1 day', '1 week', '1 month', '1 years', '1 decade', '1 century', '1 milennium');
$periods_plural = array('@count seconds', '@count minutes', '@count hours', '@count days', '@count weeks', '@count months', '@count years', '@count decades', '@count centuries', '@count milennia');
$lengths = array("60","60","24","7","4.35","12","10","10","10");
for($j = 0; $difference >= $lengths[$j]; $j++)
$difference /= $lengths[$j];
$difference = round($difference);
$text = format_plural($difference, $periods[$j], $periods_plural[$j]) .' '. t('ago');
return $text;
}
?>
Alternative from the Date module
You could also use the function theme_date_time_ago() from the Date module.