Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

round up/ round down a momentjs moment to nearest minute

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 do not want a string rounded to the nearest minute, I want a moment returned (or modified in place, either is fine). I prefer not to have to convert to a string, and the convert back too.

Thanks.


As requested, here is some code:

var now = new moment(new Date());  if (now.seconds() > 0) {     now.add('minutes', -1); }  now.seconds(0); 

as you can see, I have managed to manually round down the moment here, but it seems rather hacky. Just after a more elegant way of accomplishing this.

like image 475
bguiz Avatar asked Jul 17 '13 04:07

bguiz


People also ask

How do you round off time in a moment?

To round up or down a moment. js to the nearest minute with JavaScript, we use the startOf method. const roundDown = moment("2022-02-17 12:59:59"). startOf("hour"); roundDown.

What does rounding to the nearest minute mean?

For example, you can round time to the nearest whole minute in reports so you don't get distracted by seconds when looking at a report. Or, you can round time to the nearest 6 minutes and export them to get all time entries displayed as a nice round number with just one decimal.


2 Answers

To round up, you need to add a minute and then round it down. To round down, just use the startOf method.

Note the use of a ternary operator to check if the time should be rounded (for instance, 13:00:00 on the dot doesn't need to be rounded).

Round up/down to the nearest minute

var m = moment('2017-02-17 12:01:01'); var roundDown = m.startOf('minute'); console.log(roundDown.toString()); // outputs Tue Feb 17 2017 12:01:00 GMT+0000  var m = moment('2017-02-17 12:01:01'); var roundUp = m.second() || m.millisecond() ? m.add(1, 'minute').startOf('minute') : m.startOf('minute'); console.log(roundUp.toString());  // outputs Tue Feb 17 2017 12:02:00 GMT+0000 

Round up/down to the nearest hour

var m = moment('2017-02-17 12:59:59'); var roundDown = m.startOf('hour'); console.log(roundDown.toString()); // outputs Tue Feb 17 2017 12:00:00 GMT+0000  var m = moment('2017-02-17 12:59:59'); var roundUp = m.minute() || m.second() || m.millisecond() ? m.add(1, 'hour').startOf('hour') : m.startOf('hour'); console.log(roundUp.toString());  // outputs Tue Feb 17 2017 13:00:00 GMT+0000 
like image 63
Liyali Avatar answered Sep 23 '22 13:09

Liyali


Partial answer:

To round down to nearest moment minute:

var m = moment(); m.startOf('minute'); 

However, the equivalent for rounding up, endOf, doesn't quite give the expected result.

like image 32
bguiz Avatar answered Sep 25 '22 13:09

bguiz