Skip to content Skip to sidebar Skip to footer

Round Moment.js Object Time To Nearest 30 Minute Interval

I was trying to round the moment.js time object to next nearest 30 minute interval. But looks my logic us wrong. Ex: 10:13am -> 10:30am 11:45am -> 12:00pm Here is my current

Solution 1:

Edit 2021 : easiest solution

const start = moment('2018-12-08 09:42');
const remainder = 30 - (start.minute() % 30);
 
const dateTime = moment(start).add(remainder, "minutes").format("DD.MM.YYYY, h:mm:ss a");

console.log(dateTime);
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>

Million ways to do this. You don't need moment.js really. Anyway, here is one.

Solution 2:

Based on @Volune and @Cabloo answers and comments, an updated version can look like:

function round(date, duration, method) {
    return moment(Math[method]((+date) / (+duration)) * (+duration)); 
}

Which then can be used like:

var date = moment();
var roundedDate = round(date, moment.duration(15, "minutes"), "ceil");

Solution 3:

A generic solution:

var ROUNDING =30*60*1000; /*ms*/start= moment();
start= moment(Math.ceil((+start) / ROUNDING) * ROUNDING);
start.format("D YYYY, h:mm:ss a");

You can change ROUNDING from 30 minutes to whatever you want, and change Math.ceil by Math.round or Math.floor if you want another way to round the value.

Solution 4:

You can do it by a simple if-else clause:

if(moment().minute()> 30){
    var myTime = moment().minute(30).second(0);
} else {
    var myTime = moment().minute(0).second(0);
}

Solution 5:

You could do it with two ifs:

// Current datelet now = moment();

// Getting hour and minutelet hour   = now.hour();
let minute = now.minute();

// Rounding minute on 30 mins intervalif(minute <= 30) now.set({minute: 30});
if(minute >  30) now.set({hour: hour + 1, minute: 0});

Post a Comment for "Round Moment.js Object Time To Nearest 30 Minute Interval"