note 74652 added to function.time
| From: | CraigFrancis at osu1 dot php dot net | Date: | Sat, 21 Apr 2007 20:05:40 +0000 |
| Subject: | note 74652 added to function.time | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-125759@lists.php.net to get a copy of this message | ||
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/
----
Server IP: 194.145.210.4
Probable Submitter: 82.32.88.140
----
Manual Page -- http://www.php.net/manual/en/function.time.php
Edit -- https://master.php.net/note/edit/74652
Del: integrated -- https://master.php.net/note/delete/74652/integrated
Del: useless -- https://master.php.net/note/delete/74652/useless
Del: bad code -- https://master.php.net/note/delete/74652/bad+code
Del: spam -- https://master.php.net/note/delete/74652/spam
Del: non-english -- https://master.php.net/note/delete/74652/non-english
Del: in docs -- https://master.php.net/note/delete/74652/in+docs
Del: other reasons-- https://master.php.net/note/delete/74652
Reject -- https://master.php.net/note/reject/74652
Search -- https://master.php.net/manage/user-notes.php