note 83744 deleted from function.strtotime by derick

From: Date: Sun, 03 Aug 2008 11:53:13 +0000
Subject: note 83744 deleted from function.strtotime by derick
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-143109@lists.php.net to get a copy of this message
Note Submitter: richard at happymango dot me dot uk ---- 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 ?>

« previous php.notes (#143109) next »