note 83743 added to function.round

From: Date: Tue, 10 Jun 2008 10:41:55 +0000
Subject: note 83743 added to function.round
Groups: php.notes 
Request: Send a blank email to php-notes+get-140294@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: 87.124.64.96 Probable Submitter: 80.194.36.8 ---- Manual Page -- http://www.php.net/manual/en/function.round.php Edit -- https://master.php.net/note/edit/83743 Del: integrated -- https://master.php.net/note/delete/83743/integrated Del: useless -- https://master.php.net/note/delete/83743/useless Del: bad code -- https://master.php.net/note/delete/83743/bad+code Del: spam -- https://master.php.net/note/delete/83743/spam Del: non-english -- https://master.php.net/note/delete/83743/non-english Del: in docs -- https://master.php.net/note/delete/83743/in+docs Del: other reasons-- https://master.php.net/note/delete/83743 Reject -- https://master.php.net/note/reject/83743 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#140294) next »