note 105618 deleted from datetime.formats.relative by danbrown
| From: | danbrown@php.net | Date: | Wed, 14 Sep 2011 21:36:17 +0000 |
| Subject: | note 105618 deleted from datetime.formats.relative by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-183172@lists.php.net to get a copy of this message | ||
Note Submitter: naeon
----
If your language uses plural endings that differ from the simple english "-s", then this
function
can help you constructing a human readable string of a duration based on seconds.
The code is partially based on a similar function by http://icodesnippet.com/user/Sixer
See below examples for the format that this function returns.
<?php
/**
* readable_duration()
* Takes a duration in seconds and returns a human readable string / array
*
* @param string duration in seconds
* @param bool return concatenated string (TRUE) or array (FALSE)
* @return string or array
* @author naeon
*/
function readable_duration($seconds, $reduce_to_string = TRUE) {
$values = array(
'w' => (int) ($seconds / 86400 / 7), // weeks
'd' => $seconds / 86400 % 7, // days
'h' => $seconds / 3600 % 24, // hours
'm' => $seconds / 60 % 60, // minutes
's' => $seconds % 60); // seconds
// Example: German singulars & plurals // Deutsche Numeri
$non_english_inflections = array(
'w' => array( "Woche", "Wochen" ), // weeks
'd' => array( "Tag", "Tage" ), // days
'h' => array( "Stunde", "Stunden" ), // hours
'm' => array( "Minute", "Minuten" ), // minutes
's' => array( "Sekunde", "Sekunden" ) // seconds
);
$comma_delimiter = ","
$and_delimiter = "und" // meaning "and"
$non_zero_values = 0;
if ($reduce_to_string) {
foreach($values as $duration)
if ($duration > 0)
$non_zero_values++;
}
$result = array();
foreach ($values as $time_period => $duration) {
if ($duration > 0) {
switch ($duration) {
case 1 : $temp = $duration."
".$non_english_inflections[$time_period][0]; break;
default : $temp = $duration."
".$non_english_inflections[$time_period][1]; break;
}
if ($reduce_to_string) {
if ($non_zero_values > 2) $temp .= $comma_delimiter;
else if ($non_zero_values == 2) $temp .= " ".$and_delimiter;
$non_zero_values--;
}
$result[] = $temp;
}
}
if ($reduce_to_string)
$result = join(' ', $result);
return $result;
}
?>
Examples:
<?php
echo readable_duration("42");
// 42 Sekunden
echo readable_duration("3660");
// 1 Stunde und 1 Minute
echo readable_duration("1234567");
// 2 Wochen, 6 Stunden, 56 Minuten und 7 Sekunden
print_r(readable_duration("1234567", FALSE));
// Array
// (
// [0] => 2 Wochen
// [1] => 6 Stunden
// [2] => 56 Minuten
// [3] => 7 Sekunden
// )
?>