Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 code

start = moment();
minuteReminder = start.minute() % 30;
start.add(minuteReminder, 'minutes');
start.format("D YYYY, h:mm:ss a");
like image 852
Achintha Samindika Avatar asked Aug 15 '14 09:08

Achintha Samindika


3 Answers

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);
<script src="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.

like image 95
jtromans Avatar answered Nov 20 '22 10:11

jtromans


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");
like image 28
janhartmann Avatar answered Nov 20 '22 12:11

janhartmann


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.

like image 37
Volune Avatar answered Nov 20 '22 11:11

Volune