note 83744 added to function.strtotime
| From: | richard at happymango dot me dot uk | Date: | Tue, 10 Jun 2008 10:43:23 +0000 |
| Subject: | note 83744 added to function.strtotime | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-140295@lists.php.net to get a copy of this message | ||
If you want to round a timestamp to the closest specified increment, for example to the closest 15
minutes, then this function could help
Definition:
int roundTime ( string $increment[, int $timestamp] )
Parameters:
$increment is a string like you would for strtotime (but dont add a + or - to the front)
$timestamp (optional) the timestamp used to calculate the returned value.
Return Value:
returns timestamp
this function only works for increments less than or equal to an hour
Its not pretty but it works.
<?php
function roundTime($increment, $timestamp=0)
{
if(!$timestamp) $timestamp = time();
$increment = strtotime($increment, 1) - 1;
$this_hour = strtotime(date("Y-m-d H:", strtotime("-1 Hour",
$timestamp))."00:00");
$next_hour = strtotime(date("Y-m-d H:", strtotime("+1 Hour",
$timestamp))."00:00");
$increments = array();
$differences = array();
for($i = $this_hour; $i <= $next_hour; $i += $increment)
{
$increments []= $i;
$differences []= ($timestamp > $i)? $timestamp - $i : $i - $timestamp;
}
arsort($differences);
$key = array_pop(array_keys($differences));
return $increments[$key];
}
////////////
//EXAMPLE //
////////////
$result = roundtime("15 minutes");
echo date("H:i", time())." rounded to closest $increment is
".date("H:i", $result);
//11:24 rounded to closest 15 minutes is 11:30
?>
----
Server IP: 92.48.74.199
Probable Submitter: 80.194.36.8
----
Manual Page -- http://www.php.net/manual/en/function.strtotime.php
Edit -- https://master.php.net/note/edit/83744
Del: integrated -- https://master.php.net/note/delete/83744/integrated
Del: useless -- https://master.php.net/note/delete/83744/useless
Del: bad code -- https://master.php.net/note/delete/83744/bad+code
Del: spam -- https://master.php.net/note/delete/83744/spam
Del: non-english -- https://master.php.net/note/delete/83744/non-english
Del: in docs -- https://master.php.net/note/delete/83744/in+docs
Del: other reasons-- https://master.php.net/note/delete/83744
Reject -- https://master.php.net/note/reject/83744
Search -- https://master.php.net/manage/user-notes.php