Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

make function round up to nearest quarter hour

How can i make the function round to nearest 15 minute, not rounding down? if its 10:46 it would round to 11:00

jsfiddle: https://jsfiddle.net/31L9d08s/

code:

 var now = new Date();
    var Minutes = now.getMinutes();
    var quarterHours = Math.round(Minutes/15);
    if (quarterHours == 4)
    {
        now.setHours(now.getHours()+1);
    }
    var rounded = (quarterHours*15)%60;
    now.setMinutes(rounded);
    now.setSeconds(0);
    now.setMilliseconds(0);


    console.log(now.getTime());


    var currentdate = new Date(now.getTime()); 
    var datetime = "Last Sync: " + currentdate.getDate() + "/"
                    + (currentdate.getMonth()+1)  + "/" 
                    + currentdate.getFullYear() + " @ "  
                    + currentdate.getHours() + ":"  
                    + currentdate.getMinutes() + ":" 
                    + currentdate.getSeconds();


    console.log(datetime);
like image 216
maria Avatar asked Feb 07 '23 05:02

maria


1 Answers

How about this:

new Date(Math.ceil(new Date().getTime()/900000)*900000);

Explanation: new Date().getTime() returns the current time in the form of a unix timestamp (i.e. the number of milliseconds since 1970-01-01 00:00 UTC), which we round up to the nearest multiple of 900000 (i.e. the number of milliseconds in a quarter-hour) with the help of Math.ceil.

Edit: If you want to apply this to intervals other than 15 minutes, you can do it like that (e.g. for 30 minutes):

var interval = 30 * 60 * 1000; // 30 minutes in milliseconds
new Date(Math.ceil(new Date().getTime()/interval)*interval);
like image 169
redneb Avatar answered Feb 08 '23 19:02

redneb