Reputation: 542
I have a time string in UNIX format . I need to round that string to closest interval of 30 minutes.
For eg: I have time as 9:20 AM than it should round it to 9:30 AM.
If minutes are greater than 30 like 9:45 AM it should round to 10:00 AM.
I have tried this so far:
$hour = date('H', $ltdaytmfstr);
$minute = (date('i', $ltdaytmfstr)>30)?'00':'30';
echo "$hour:$minute";
$ltdaytmfstr
is time string in unix format.
Any suggestions? It would be better if I can get the value returned in UNIX format .
Upvotes: 3
Views: 1923
Reputation: 905
I guess this is what you are looking for
function round_timestamp($timestamp){
$hour = date("H", strtotime($timestamp));
$minute = date("i", strtotime($timestamp));
if ($minute<15) {
return date('H:i', strtotime("$hour:00") );
} elseif($minute>=15 and $minute<45){
return date('H:i', strtotime("$hour:30") );
} elseif($minute>=45) {
$hour = $hour + 1;
return date('H:i', strtotime("$hour:00") );
}
}
echo round_timestamp("11:59");
// 00:00
echo round_timestamp("10:59");
// 11:00
Upvotes: 2
Reputation: 3294
You should try this: This will round it to the nearest half an hour.
Use ceil
function.
<?php
$rounded = date('H:i:s', ceil(strtotime('16:20:34')/1800)*1800);
echo $rounded;
?>
Output: 16:30:00
Upvotes: 6
Reputation: 40683
If you use DateTime:
$dt = new \DateTime;
$diff = $dt
->add(
//This just calculates number of seconds from the next 30 minute interval
new \DateInterval("PT".((30 - $dt->format("i"))*60-$dt->format("s"))."S")
);
echo $dt->getTimestamp();
Upvotes: 2
Reputation: 59287
Since UNIX time is in seconds, you can just transform it to 30 minute units, round, and convert back to seconds.
$timestamp = time();
$rounded = round($timestamp / (30 * 60)) * 30 * 60
You can also use floor()
or ceil()
to round up or down if needed.
Upvotes: 1