How do you round up/ round down a momentjs moment to nearest minute?
I have checked the docs, but there doesn\'t appear to be a method for this.
Note that I
Easy. As stated by many others, just use Moment.startOf:
var roundDown = moment('2015-02-17 12:59:59').startOf('hour');
roundDown.format('HH:mm:SS'); // 12:00:00
Importantly, this also works as expected:
var roundDown = moment('2015-02-17 12:00:00').startOf('hour');
roundDown.format('HH:mm:SS'); // 12:00:00
Slightly trickier, if we want to round up with a proper ceiling function: for example, when rounding up by hour, we want 12:00:00 to round up to 12:00:00.
var roundUp = moment('2015-02-17 12:00:00').add(1, 'hour').startOf('hour');
roundUp.format('HH:mm:SS'); // ERROR: 13:00:00
function roundUp(momentObj, roundBy){
return momentObj.add(1, roundBy).startOf(roundBy);
}
var caseA = moment('2015-02-17 12:00:00');
roundUp(caseA, 'minute').format('HH:mm:SS'); // 12:00:00
var caseB = moment('2015-02-17 12:00:00.001');
roundUp(caseB, 'minute').format('HH:mm:SS'); // 12:01:00
var caseC = moment('2015-02-17 12:00:59');
roundUp(caseC, 'minute').format('HH:mm:SS'); // 12:01:00