The setTime()
and getTime()
methods of the Date
object can be used to increment or decrement hours from a date in JavaScript.
The following example demonstrates how you can add 3 hours to the current date:
const today = new Date()
const afterThreeHours = new Date()
// Add 3 Hours
afterThreeHours.setTime(today.getTime() + 3 * 60 * 60 * 1000)
The getTime()
method returns the number of milliseconds elapsed between January 1st, 1970, at 00:00:00 UTC and the given date.
The setTime()
method takes a number representing the milliseconds since January 1st, 1970, at 00:00:00 UTC and sets the value on the given date.
You can also update the existing JavaScript Date
object as shown below:
const date = new Date()
date.setTime(date.getTime() + 3 * 60 * 60 * 1000)
To subtract hours from a date in JavaScript, simply minus the number of milliseconds when updating the date with the setTime()
method:
const today = new Date()
const lastHour = new Date()
// Minus 1 Hour
lastHour.setTime(today.getTime() - 1 * 60 * 60 * 1000)
Finally, if you are frequently manipulating dates in JavaScript, add a function to Date
’s prototype and call it directly whenever you want to add or subtract hours:
Date.prototype.addHours = function (hours) {
const date = new Date(this.valueOf())
date.setTime(date.getTime() + hours * 60 * 60 * 1000)
return date
}
// Add 1 Hour
const nextHour = new Date(2022, 10, 15)
console.log(nextHour.addHours(1))
// Tue Nov 15 2022 01:00:00 GMT+0500 (Pakistan Standard Time)
// Minus 1 Hour
const lastHour = new Date(2022, 10, 15)
console.log(lastHour.addHours(-1))
// Mon Nov 14 2022 23:00:00 GMT+0500 (Pakistan Standard Time)