johnsmith153 Posted August 19, 2010 Share Posted August 19, 2010 I need to take a time and convert so it is rounded up or down to the nearest 0 or 5. function roundMe ($time, $upDown) { if($upDown==1) { //round up } else { //round down } return $x; } echo roundMe("16:22", 1); // returns 16:25 echo roundMe("16:22", 0); // returns 16:20 echo roundMe("16:25", 1); // returns 16:25 echo roundMe("16:59", 1); // returns 17:00 echo roundMe("16:59", 0); // returns 16:55 Link to comment https://forums.phpfreaks.com/topic/211190-round-to-nearest-0-or-5/ Share on other sites More sharing options...
DavidAM Posted August 19, 2010 Share Posted August 19, 2010 If $time is always a string with a colon in it: function roundMe ($time, $upDown) { list($hrs, $mins) = explode(':', $time); // Is it already on a 5-minute boundary? if (($mins % 5) == 0) return $time; if($upDown==1) { //round up $mins += 5 - ($mins % 5); } else { //round down $mins -= ($mins % 5); } if ($mins < 10) $mins = '0' . $mins; return $hrs . ':' . $mins; } Link to comment https://forums.phpfreaks.com/topic/211190-round-to-nearest-0-or-5/#findComment-1101280 Share on other sites More sharing options...
johnsmith153 Posted August 19, 2010 Author Share Posted August 19, 2010 Brilliant, thanks, but my 5 tests (sown in my first post) would return: 16:25 16:20 16:25 16:60 16:55 I'm looking at a fix myself. Thanks for dong most of it though. Link to comment https://forums.phpfreaks.com/topic/211190-round-to-nearest-0-or-5/#findComment-1101289 Share on other sites More sharing options...
johnsmith153 Posted August 19, 2010 Author Share Posted August 19, 2010 if($mins==60) { $hrs++; $mins = "00"; } Link to comment https://forums.phpfreaks.com/topic/211190-round-to-nearest-0-or-5/#findComment-1101290 Share on other sites More sharing options...
johnsmith153 Posted August 19, 2010 Author Share Posted August 19, 2010 if($hrs==24) { $hrs = "00"; } Link to comment https://forums.phpfreaks.com/topic/211190-round-to-nearest-0-or-5/#findComment-1101292 Share on other sites More sharing options...
DavidAM Posted August 19, 2010 Share Posted August 19, 2010 Oops! Sorry, I forgot about the hours thing. Looks like you fingured it out though. By the way, click the "Solved" button at the bottom of the post so others can see that there is a solution to the question. It's almost at the bottom of the page. Link to comment https://forums.phpfreaks.com/topic/211190-round-to-nearest-0-or-5/#findComment-1101346 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.