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");
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.
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");
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With