Time Slot calculation for 10 or 60 minute interval
October 30, 2023· Tech
Suppose a situation where you want to store data in a way like <current_time+10min>
but every time current_time + 10 mins return a new value, we want to settle time in a way like a store at 00, 10, 20,30,40,50 min slot.
See some example
Slot for 10 minute interval
23 Oct, 2023 17:23:32 ===> 23 Oct, 2023 17:30:0023 Oct, 2023 17:53:32 ===> 23 Oct, 2023 18:00:0023 Oct, 2023 23:53:32 ===> 24 Oct, 2023 00:00:00
Slot for 60 minute interval23 Oct, 2023 17:13:32 ===> 23 Oct, 2023 18:00:0023 Oct, 2023 23:53:32 ===> 24 Oct, 2023 00:00:00
Here I used the node.js moment library to give you the solution:
js
const moment = require('moment');
function getRoundedTimeSlot(timeStr, minutesInterval = 10) {
const m = moment(timeStr, 'DD MMM, YYYY HH:mm:ss');
const remainder = m.minute() % minutesInterval;
return m.add(minutesInterval - remainder, 'minutes').startOf('minute').format('DD MMM, YYYY HH:mm:ss');
}
// Examples
console.log(getRoundedTimeSlot('23 Oct, 2023 17:23:32', 10)); // '23 Oct, 2023 17:30:00'
console.log(getRoundedTimeSlot('23 Oct, 2023 17:13:32', 60)); // '23 Oct, 2023 18:00:00'