How to round time to the nearest half hour?

0
How can I write a function to round the CurrentDateTime to the nearest half hour or a half hour? I have tried using trimHours but that just changes the minutes to zero   Example 1: 9:31 AM --> 10:00 AM Example 2: 9:31 AM -> 9:30 AM
asked
1 answers
1

An easy approach would be to calculate the minutes between the trimmed and actual time, then round that to multiples of 30 and add it again to the trimmedTime.

Should be a simple calculation like below (not tested, though)

$time
$trimmedTime = trimToHours($time)
$minutes = minutesBetween( $trimmedTime, $time)
$roundedMinutes= round( $minutes : 30 ) * 30
$roundedTime = addMinutes( $trimmedTime, $roundedMinutes)

regards, Fabian

answered