请注意,我不希望将字符串四舍五入到最接近的分钟,我希望返回moment(或在适当位置进行修改,都可以).我希望不必将其转换为字符串,也不必将其转换回去.谢谢.根据要求,下面是一些代码:var now = new moment(new Date());if (now.seconds() > 0) { now.add('minutes', -1);}now.seconds(0);如您所见,我设法在此处手动舍入了这一点,但是似乎很不客气.只是在以一种更优雅的方式完成此操作之后.解决方案要进行四舍五入,您需要添加一分钟,然后将其四舍五入.要四舍五入,只需使用startOf方法.请注意,使用三元运算符检查时间是否应舍入(例如,,圆点上的13:00:00不需要舍入).向上/向下舍入到最近的分钟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+0000var 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向上/向下舍入到最近的小时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+0000var 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+0000How 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. 解决方案 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 minutevar 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+0000var 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+0000Round up/down to the nearest hourvar 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+0000var 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 这篇关于四舍五入/四舍五入js矩到最近的分钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-28 04:51