Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding up to nearest available time slot in PHP

Tags:

date

php

rounding

I've been struggling with this for an hour or so and have come up blank. Basically I need to take the current time, add 30 minutes to it, and then round up to the next 15 minutes.

Examples:

  • if it's now 20:00, result = 20:45
  • if it's now 20:10, result = 20:45
  • if it's now 20:16, result = 21:00
  • if it's now 20:35, result = 21:15

My PHP is rusty and I've been getting mixed up with date add and round methods trying to get this to work and I know it's simple - have just run out of ideas!

Thanks

like image 424
Russ Back Avatar asked Mar 01 '12 20:03

Russ Back


Video Answer


2 Answers

I'll add a solution as well:

<?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('m-d-Y H:i', $time) . ' becomes ' . date('m-d-Y H:i:s', roundToNearestInterval($time)) . "<br />\n";
}


function roundToNearestInterval($timestamp)
{
    $timestamp += 60 * 30;
    list($m, $d, $y, $h, $i, $s) = explode(' ', date('m d Y H 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);
}

Yields:

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
like image 154
drew010 Avatar answered Sep 22 '22 00:09

drew010


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

like image 31
halfer Avatar answered Sep 21 '22 00:09

halfer