maria maria - 3 months ago 15
Javascript Question

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

Answer

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