note 74652 deleted from function.time by nlopess
| From: | nlopess@php.net | Date: | Tue, 01 May 2007 13:40:01 +0000 |
| Subject: | note 74652 deleted from function.time by nlopess | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-126044@lists.php.net to get a copy of this message | ||
Note Submitter: Craig Francis
----
If you have a number of seconds, and want a human friendly way of expressing it, try the
following...
<?php
function unix2human($unix) {
//--------------------------------------------------
// Maths
$sec = $unix % 60;
$unix -= $sec;
$minSeconds = $unix % 3600;
$unix -= $minSeconds;
$min = ($minSeconds / 60);
$hourSeconds = $unix % 86400;
$unix -= $hourSeconds;
$hour = ($hourSeconds / 3600);
$daySeconds = $unix % 604800;
$unix -= $daySeconds;
$day = ($daySeconds / 86400);
$week = ($unix / 604800);
//--------------------------------------------------
// Text
$output = '';
if ($week > 0) $output .= ', ' . $week . ' week' . ($week != 1 ?
's' : '');
if ($day > 0) $output .= ', ' . $day . ' day' . ($day != 1 ?
's' : '');
if ($hour > 0) $output .= ', ' . $hour . ' hour' . ($hour != 1 ?
's' : '');
if ($min > 0) $output .= ', ' . $min . ' minute' . ($min != 1 ?
's' : '');
if ($sec > 0 || $output == '') {
$output .= ', ' . $sec . ' second' . ($sec != 1 ? 's' :
'');
}
//--------------------------------------------------
// Grammar
$output = preg_replace('/^, /', '', $output);
$output = preg_replace('/, ([^,]+)$/', ' and $1', $output);
//--------------------------------------------------
// Return the output
return $output;
}
echo unix2human(30);
// OUTPUT: 30 seconds
echo unix2human(183);
// OUTPUT: 3 minutes and 3 seconds
echo unix2human(237905);
// OUTPUT: 2 days, 18 hours, 5 minutes and 5 seconds
echo unix2human(strtotime('18:00') - strtotime('16:20'));
// OUTPUT: 1 hour and 40 minutes
?>
http://www.craigfrancis.co.uk/features/code/phpHumanTime/