How to round unix timestamp up and down to nearest half hour? How to round unix timestamp up and down to nearest half hour? php php

How to round unix timestamp up and down to nearest half hour?


Use modulo.

$prev = 1330518155 - (1330518155 % 1800);$next = $prev + 1800;

The modulo operator gives the remainder part of division.


I didn't read the questions clearly, but this code will round to the nearest half hour, for those who don't need the range between the two. Uses some of SenorAmor's code. Props and his mad elegant solution to the correct question.

$time = 1330518155; //Or whatever your time is in unix timestamp//Store how many seconds long our rounding interval is//1800 equals one half hour//Change this to whatever interval to round by$INTERVAL_SECONDS = 1800;  //30*60//Find how far off the prior interval we are$offset = ($time % $INTERVAL_SECONDS); //Removing this offset takes us to the "round down" half hour$rounded = $time - $offset; //Now add the full interval if we should have rounded upif($offset > ($INTERVAL_SECONDS/2)){  $nearestInterval = $rounded + $INTERVAL_SECONDS;}else{  $nearestInterval = $rounded }


You could use the modulo operator.

$time -= $time % 3600; // nearest hour (always rounds down)

Hopefully this is enough to point you in the right direction, if not please add a comment and I'll try to craft a more specific example.