round up/ round down a momentjs moment to nearest minute

后端 未结 10 1460
一整个雨季
一整个雨季 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 02:22

    Rounding Down

    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
    

    Rounding Up

    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.

    This does not work

    var roundUp = moment('2015-02-17 12:00:00').add(1, 'hour').startOf('hour');
    roundUp.format('HH:mm:SS'); // ERROR: 13:00:00
    

    Solution

    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
    

提交回复
热议问题