Search code examples
javascriptdatetimetimehour

How to round to nearest hour and minutes by incremment in JavaScript without using moment.js?


Expected Result

Round Off Time : 15 min

Given Time 10:00 => Rounded to: 10:00

Given Time 10:13 => Rounded to: 10:15

Given Time 10:15 => Rounded to: 10:15

Given Time 10:16 => Rounded to: 10:30

Given Time 16:00 => Rounded to: 16:00

Given Time 16:12 => Rounded to: 16:15

Round Off Time varies based on user input

MyCode

var m = (((minutes + 7.5)/roundOffTime | 0) * roundOffTime) % 60;
var h = ((((minutes/105) + .5) | 0) + hours) % 24;

Current Output

Given time: 08:22 => Rounded to: 08:15

Given time: 08:23 => Rounded to: 08:30

Need round off time should be in increment order


Solution

  • You could take all minutes and divide by 15 for getting the whole quarter and multiply by 15 for the result. Then take hours and minutes and apply formatting. Return joined values.

    function roundMinutes(t) {
        function format(v) { return v < 10 ? '0' + v: v; }
    
        var m = t.split(':').reduce(function (h, m) { return h * 60 + +m; });
        
        m = Math.ceil(m / 15) * 15;
        return [Math.floor(m / 60), m % 60].map(format).join(':');
    }
    
    var data = ['10:00', '10:13', '10:15', '10:16', '16:00', '16:12', '16:55'];
    
    console.log(data.map(roundMinutes));