Sometimes, we may need to round off time or duration, on quarterly basis. The below table explains it better:
Actual time | Quarterly rounded |
00:12 | 00:15 |
01:07 | 01:00 |
02:25 | 02:30 |
00:52 | 01:00 |
00:04 | 00:00 |
To round the time or duration quarterly, you first need to have the duration saved in seconds. Let’s assume that there’s a duration of 2 hours and 25 mins which we need to round off quarterly.
2 hours and 25 minutes would equal to 8700 seconds. So, the function to convert it would look like:
function getHoursAndMinsRounded(durationInSeconds) {
const durationInMinutes = durationInSeconds / 60
let hours = durationInMinutes / 60
const roundedHours = Math.floor(hours)
const minutes = (hours - roundedHours) * 60
const h = minutes > 52 ? (hours === 23 ? 0 : ++hours) : hours
const m = (Math.round(minutes / 15) * 15) % 60
return `${parseInt(h.toString())}:${m.toString()}`
}
console.log(getHoursAndMinsRounded(8700))
//output
2:30
Code language: JavaScript (javascript)
The output of the above code would be 2:30. You can of course, also add zero padding if you need to. I’ve already written an article on adding zero padding here. The result would then look like 02:30 instead.