Round moment.js object time to nearest 30 minute i

2019-02-01 17:20发布

问题:

I was trying to round the moment.js time object to next nearest 30 minute interval. But looks my logic us wrong. Can someone help me. 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");

回答1:

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.



回答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");


回答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.



回答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);
            }


回答5:

even though the question has been answered, I'd like to share my solution too.

var moment = require('moment');

const roundToNearestXXMinutes = (dateTime, roundTo) => {
    let remainder = roundTo - (start.minute()+ start.second()/60) % roundTo ;
    //console.log(moment(start).format("DD.MM.YYYY HH:mm:ss"));
    remainder = (remainder >  roundTo/2) ? remainder = -roundTo + remainder : remainder;
    const changedDate = moment(start).add(remainder, "minutes" ).seconds(0).format("DD.MM.YYYY HH:mm:ss");
    //console.log('is changed to');
    //console.log(changedDate);
}

roundToNearestXXMinutes(new Date("October 13, 2014 23:46:00"), 10);