Rounding to the closest available time interval in PHP

I struggled with this for an hour or so and came to my senses. Basically I need to take the current time, add 30 minutes to it, and then round to the next 15 minutes.

Examples:

  • if it is now 20:00, the result = 20:45
  • if he is now 20:10, result = 20:45
  • if he is now 20:16, the result = 21:00
  • if he is now 20:35, result = 21:15

My PHP is rusty, and I mixed up with date adding and round methods trying to get this to work, and I know it's simple - you just ran out of ideas!

thanks

+6
source share
4 answers

I will also add a solution:

<?php date_default_timezone_set('America/Los_Angeles'); $times = array(); $times[] = strtotime('00:07'); $times[] = strtotime('04:21'); $times[] = strtotime('20:00'); $times[] = strtotime('20:10'); $times[] = strtotime('20:16'); $times[] = strtotime('20:35'); $times[] = strtotime('23:15'); foreach($times as $time) { echo date('mdY H:i', $time) . ' becomes ' . date('mdY H:i:s', roundToNearestInterval($time)) . "<br />\n"; } function roundToNearestInterval($timestamp) { $timestamp += 60 * 30; list($m, $d, $y, $h, $i, $s) = explode(' ', date('md YH i s', $timestamp)); if ($s != 0) $s = 0; if ($i < 15) { $i = 15; } else if ($i < 30) { $i = 30; } else if ($i < 45) { $i = 45; } else if ($i < 60) { $i = 0; $h++; } return mktime($h, $i, $s, $m, $d, $y); } 

Productivity:

 03-01-2012 00:07 becomes 03-01-2012 00:45:00 03-01-2012 04:21 becomes 03-01-2012 05:00:00 03-01-2012 20:00 becomes 03-01-2012 20:45:00 03-01-2012 20:10 becomes 03-01-2012 20:45:00 03-01-2012 20:16 becomes 03-01-2012 21:00:00 03-01-2012 20:35 becomes 03-01-2012 21:15:00 03-01-2012 23:15 becomes 03-02-2012 00:00:00 
+6
source

Something like this: convert to unix timestamp, add 30 * 60, then divide by 15 * 60, apply ceil (), then multiply by 15 * 60, and then convert back to the date.

+2
source

You may need to update this version a bit and test several scenarios where the time is close to the beginning of the hour.

 <?php $now = strtotime('now'); $timePlus30 = date('H:i', strtotime('+30 minutes', $now)); $minNow = date('i', strtotime($timePlus30)); $roundedMins = $minNow + ($minNow % 15); $return = date('H', strtotime($timePlus30)) . ':' . ($roundedMins - 1); ?> 
+2
source

not the most elite solution, but it should work (not verified)

 $hoursAndMins = explode(":",timeString); // should be "HH:MM" $hours = $hoursAndMins[0]+(($hoursAndMins[1]+30)/60); $mins = ($hoursAndMins[1]+30)%60; if ($mins > 52){ $mins = "00"; $hours += 1; }else if ($mins > 38){ $mins = "45"; }else if ($mins > 23){ $mins = "30"; }else if( $mins > 7){ $mins = "15"; }else{ $mins = "00"; } echo $hours+ ":"+$mins; 

[edit] Another solution is much better, I think, but this one is more detailed.

0
source

Source: https://habr.com/ru/post/909779/


All Articles