Alex Rivera | Logout

Round minute down to nearest quarter hour

Asked 2010-03-19T21:15:37.940
65

I need to round times down to the nearest quarter hour in PHP. The times are being pulled from a MySQL database from a datetime column and formatted like 2010-03-18 10:50:00.

Example:

  • 10:50 needs to be 10:45
  • 1:12 needs to be 1:00
  • 3:28 needs to be 3:15
  • etc.

I'm assuming floor() is involved but not sure how to go about it.

Thanks

Edit
Report

2 Answers

1

I needed a way to round down to the day, and cut off everything beyond that:

$explodedDate = explode("T", gmdate("c",strtotime("now")));
$expireNowDate =  date_create($explodedDate[0]);

The strtotime gives me a timestamp for "now", which gmdate converts to ISO format (something like "2012-06-05T04:00:00+00:00"), then I use explode at the "T", giving me "2012-06-05" in the zeroth index of $explodedDate, which is then passed into date_create to get a date object.

Not sure if all of that is necessary, but it seems like a lot less work than going through and subtracting the seconds, minutes, hours etc.

answered 2011-12-08T14:10:20.940
0

I wrote a function that does the trick to round time stamps to seconds or minutes.

I might not be the most performant way, but I think PHP doens't care about a few simple loops.

In your case, you just pass your MySQL datetime like this:

<?php echo date('d/m/Y - H:i:s', roundTime(strtotime($MysqlDateTime), 'i', 15)); ?>

Returns: the closests rounded value (looks both up and down!)

The function:

<?php
function roundTime($time, $entity = 'i', $value = 15){

    // prevent big loops
    if(strpos('is', $entity) === false){
        return $time;
    }

    // up down counters
    $loopsUp = $loopsDown = 0;

    // loop up
    $loop = $time;
    while(date($entity, $loop) % $value != 0){
        $loopsUp++;
        $loop++;
    }
    $return = $loop;    


    // loop down
    $loop = $time;
    while(date($entity, $loop) % $value != 0){
        $loopsDown++;
        $loop--;
        if($loopsDown > $loopsUp){
            $loop = $return;
            break;  
        }
    }
    $return = $loop;

    // round seconds down
    if($entity == 'i' && date('s', $return) != 0){
        while(intval(date('s', $return)) != 0){
            $return--;
        }
    }
    return $return;
}
?>

You simple replace $entity by 's' if you want to round up or down to seconds and replace 15 by the amount of seconds or minutes you want to roud up or down to.

answered 2012-12-05T13:55:42.887

Your Answer