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

前端 未结 8 1220
醉话见心
醉话见心 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:07

    There is an NPM package @qc/date-round that can be used. Given that you have a Date instance to be rounded

    import { round } from '@qc/date-round'
    
    const dateIn = ...; // The date to be rounded
    const interval = 5 * 60 * 1000; // 5 minutes
    const dateOut = round(dateIn, interval)
    

    Then you can use date-fns to format the date

    import format from 'date-fns/format';
    
    console.log(format(dateOut, 'HH:mm')) // 24-hr
    console.log(format(dateOut, 'hh:mm a')) // 12-hr
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题