开发者

How to round to nearest hour using JavaScript Date Object

I am working on a project that requires a time in the future to be set using the Date object.

For example:

futureTime = new Date();
f开发者_运维知识库utureTime.setHours(futureTime.getHours()+2);

My questions is; once the future date is set, how can I round to the closest full hour and then set the futureTime var with it?

For example:

Given 8:55 => var futureTime = 9:00
Given 16:23 => var futureTime = 16:00

Any help would be appreciated!


Round the minutes and then clear the minutes:

var date = new Date(2011,1,1,4,55); // 4:55
roundMinutes(date); // 5:00

function roundMinutes(date) {

    date.setHours(date.getHours() + Math.round(date.getMinutes()/60));
    date.setMinutes(0, 0, 0); // Resets also seconds and milliseconds

    return date;
}


The other answers ignore seconds and milliseconds components of the date.

The accepted answer has been updated to handle milliseconds, but it still does not handle daylight savings time properly.

I would do something like this:

function roundToHour(date) {
  p = 60 * 60 * 1000; // milliseconds in an hour
  return new Date(Math.round(date.getTime() / p ) * p);
}

var date = new Date(2011,1,1,4,55); // 4:55
roundToHour(date); // 5:00

date = new Date(2011,1,1,4,25); // 4:25
roundToHour(date); // 4:00


A slightly simpler way :

var d = new Date();
d.setMinutes (d.getMinutes() + 30);
d.setMinutes (0);


Another solution, which is no where near as graceful as IAbstractDownvoteFactory's

var d = new Date();
if(d.getMinutes() >= 30) {
   d.setHours(d.getHours() + 1);
}
d.setMinutes(0);


Or you could mix the two for optimal size. http://jsfiddle.net/HkEZ7/

function roundMinutes(date) {
    return date.getMinutes() >= 30 ? date.getHours() + 1 : date.getHours();
}


As a matter of fact Javascript does this default which gives wrong time.

let dateutc="2022-02-17T07:20:00.000Z";
let bd = new Date(dateutc);
console.log(bd.getHours()); // gives me 8!!!!!

it is even wrong for my local time because I am GMT+2 so it should say 9. moment.js also does it wrong so you need to be VERY carefull


Pass any cycle you want in milliseconds to get next cycle example 1 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(1 * 60 * 60 * 1000)); // 1 hours in milliseconds

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜