Home > database >  add hours to date not working as expected
add hours to date not working as expected

Time:11-13

I want to add hours to date using this function:

function addHoursToDate(date, hours) {
    return new Date(new Date(date).setHours(date.getHours()   hours));
}

const now = new Date();

console.log('now', now);

console.log('then', addHoursToDate(now, 1));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

The weird issue is here on SO we get the correct result but if you use the same code on node.js both logs are the same.

How can I fix this?

enter image description here

CodePudding user response:

You can do it without function

const now = new Date();

console.log('now', now);
now.setHours(now.getHours()   1)
console.log('then', now);

or with function

function addHoursToDate(date, hours) {
date.setHours(date.getHours()   hours)
    return date;
}
const now = new Date();
console.log('now', now);
console.log('then', addHoursToDate(now, 1));
  • Related