note 74731 added to function.time
| From: | webmaster | Date: | Wed, 25 Apr 2007 14:36:04 +0000 |
| Subject: | note 74731 added to function.time | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-125857@lists.php.net to get a copy of this message | ||
In a recent object I had to calculate the time difference between timestamps in a string format, so
I wrote this nice little function I'd like to share.
<?php
define('INT_SECOND', 1);
define('INT_MINUTE', 60);
define('INT_HOUR', 3600);
define('INT_DAY', 86400);
define('INT_WEEK', 604800);
function get_formatted_timediff($then, $now = false)
{
$now = (!$now) ? time() : $now;
$timediff = ($now - $then);
$weeks = (int) intval($timediff / INT_WEEK);
$timediff = (int) intval($timediff - (INT_WEEK * $weeks));
$days = (int) intval($timediff / INT_DAY);
$timediff = (int) intval($timediff - (INT_DAY * $days));
$hours = (int) intval($timediff / INT_HOUR);
$timediff = (int) intval($timediff - (INT_HOUR * $hours));
$mins = (int) intval($timediff / INT_MINUTE);
$timediff = (int) intval($timediff - (INT_MINUTE * $mins));
$sec = (int) intval($timediff / INT_SECOND);
$timediff = (int) intval($timediff - ($sec * INT_SECOND));
$str = '';
if ( $weeks )
{
$str .= intval($weeks);
$str .= ($weeks > 1) ? ' weeks' : ' week';
}
if ( $days )
{
$str .= ($str) ? ', ' : '';
$str .= intval($days);
$str .= ($days > 1) ? ' days' : ' day';
}
if ( $hours )
{
$str .= ($str) ? ', ' : '';
$str .= intval($hours);
$str .= ($hours > 1) ? ' hours' : ' hour';
}
if ( $mins )
{
$str .= ($str) ? ', ' : '';
$str .= intval($mins);
$str .= ($mins > 1) ? ' minutes' : ' minute';
}
if ( $sec )
{
$str .= ($str) ? ', ' : '';
$str .= intval($sec);
$str .= ($sec > 1) ? ' seconds' : ' second';
}
if ( !$weeks && !$days && !$hours && !$mins && !$sec )
{
$str .= '0 seconds ago';
}
else
{
$str .= ' ago';
}
return $str;
}
?>
----
Server IP: 69.147.83.197
Probable Submitter: 124.184.224.11
----
Manual Page -- http://www.php.net/manual/en/function.time.php
Edit -- https://master.php.net/note/edit/74731
Del: integrated -- https://master.php.net/note/delete/74731/integrated
Del: useless -- https://master.php.net/note/delete/74731/useless
Del: bad code -- https://master.php.net/note/delete/74731/bad+code
Del: spam -- https://master.php.net/note/delete/74731/spam
Del: non-english -- https://master.php.net/note/delete/74731/non-english
Del: in docs -- https://master.php.net/note/delete/74731/in+docs
Del: other reasons-- https://master.php.net/note/delete/74731
Reject -- https://master.php.net/note/reject/74731
Search -- https://master.php.net/manage/user-notes.php