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

前端 未结 8 1260
醉话见心
醉话见心 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条回答
  •  长情又很酷
    2020-12-04 22:14

    Round to nearest x minutes

    Here is a method that will round a date object to the nearest x minutes, or if you don't give it any date it will round the current time.

    let getRoundedDate = (minutes, d=new Date()) => {
    
      let ms = 1000 * 60 * minutes; // convert minutes to ms
      let roundedDate = new Date(Math.round(d.getTime() / ms) * ms);
    
      return roundedDate
    }
    
    
    // USAGE //
    
    // Round existing date to 5 minutes
    getRoundedDate(5, new Date()); // 2018-01-26T00:45:00.000Z
    
    // Get current time rounded to 30 minutes
    getRoundedDate(30); // 2018-01-26T00:30:00.000Z
    

提交回复
热议问题