maria
maria

Reputation: 159

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);

Upvotes: 5

Views: 3814

Answers (2)

Shubham Rai
Shubham Rai

Reputation: 39

Pass any cycle you want in milliseconds to get next cycle example 2,4,8 hours

function calculateNextCycle(interval) {
    const timeStampCurrentOrOldDate = Date.now();
    const timeStampStartOfDay = new Date().setHours(0, 0, 0, 0);
    const timeDiff = timeStampCurrentOrOldDate - timeStampStartOfDay;
    const mod = Math.ceil(timeDiff / interval);
    return new Date(timeStampStartOfDay + (mod * interval));
}

console.log(calculateNextCycle(4 * 60 * 60 * 1000)); // 4 hours in milliseconds

Upvotes: 0

redneb
redneb

Reputation: 23870

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);

Upvotes: 9

Related Questions