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

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

    recently found a very efficient way to round off the date to a timeframe

    in short:

    // minutes
    var tf = 15; // 5,10,13,15, 60, - what ever you want
    var dt = DateTime.UtcNow;
    var minues = dt.TimeOfDay.TotalMinutes; // use TotalMinutes, TotalSecibds, TotalMillisecons  and etc
    var roundedMinutes = (minues - (minues%tf));
    var roundedDate = dt.Date.AddMinutes(a);
    

    I bit of my testing in LINQPad

    // minutes
    var tf = 15; // 5,10,13,15, 60, - what ever you want
    var dt = DateTime.UtcNow;
    var minues = dt.TimeOfDay.TotalMinutes;
    dt.Dump();
    minues.Dump();
    (ms%tf).Dump();
    var a = (minues - (minues%tf));
    a.Dump();
    dt.Date.AddMinutes(a).Dump();
    

    output:

    13.07.2018 7:43:58 - current date
    463,981443103333 - total mins
    13,9814431033333 - rest
    450 - rounded minutes value
    13.07.2018 7:30:00 - rounded date
    

提交回复
热议问题