Round a Date() to the nearest 5 minutes in javascript

前端 未结 8 1264
醉话见心
醉话见心 2020-12-04 21:48

Using a Date() instance, how might I round a time to the nearest five minutes?

For example: if it\'s 4:47 p.m. it\'ll set the time to 4:45 p.m.

8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-04 22:02

    Probably less efficient but here's another alternative:

    debug('Current timestamp:', timestamp);
    
    timestamp.setMilliseconds(0);
    timestamp.setSeconds(0);
    timestamp.setMinutes(Math.round(timestamp.getMinutes() / 5) * 5);
    
    debug('Rounded timestamp:', timestamp);
    
    Current timestamp: 2019-10-22T09:47:17.989Z
    Rounded timestamp: 2019-10-22T09:45:00.000Z
    

提交回复
热议问题