round up/ round down a momentjs moment to nearest minute

后端 未结 10 1421
一整个雨季
一整个雨季 2020-12-05 01:47

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

相关标签:
10条回答
  • 2020-12-05 01:55

    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
    
    0 讨论(0)
  • 2020-12-05 01:57

    The roundTo feature could make it into a future release.

    Examples:

    moment().roundTo('minute', 15); // output: 12:45
    moment().roundTo('minute', 15, 'down'); // output: 12:30
    
    0 讨论(0)
  • 2020-12-05 01:59

    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.

    0 讨论(0)
  • 2020-12-05 02:00

    This solution worked for me;

    function round_up_to_nearest_hour(date = new Date()) {
       return moment(date).add(59, 'minutes').startOf('hour').toDate();
    }
    
    0 讨论(0)
  • 2020-12-05 02:01

    Rounding to the nearest hour can be achieved by adding half an hour and then run .startOf('hour'). This is the same for any time measurement.

    var now = moment();
    // -> Wed Sep 30 2015 11:01:00
    now.add(30, 'minutes').startOf('hour'); // -> Wed Sep 30 2015 11:31:00
    // -> Wed Sep 30 2015 11:00:00
    
    var now = moment();
    // -> Wed Sep 30 2015 11:31:00
    now.add(30, 'minutes').startOf('hour'); // -> Wed Sep 30 2015 12:01:00
    // -> Wed Sep 30 2015 12:00:00
    
    0 讨论(0)
  • 2020-12-05 02:04

    Just another possibility:

    var now = moment();
    // -> Wed Sep 30 2015 11:57:20 GMT+0200 (CEST)
    now.add(1, 'm').startOf('minute');
    // -> Wed Sep 30 2015 11:58:00 GMT+0200 (CEST)
    
    0 讨论(0)
提交回复
热议问题