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

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

提交回复
热议问题