How to add hours to a date in JavaScript

published: 20 Sep 2022

2 min read

How to add hours to a date in JavaScript

To add hours to date in JavaScript:

  1. Use the getTime() method to get the number of milliseconds since Unix Epoch.
  2. Call the setTime() method and pass it the number of milliseconds returned by getTime(), plus the hours you want to add in milliseconds.

The following example demonstrates how you can add 4 hours to the current date in JavaScript:

const today = new Date()
today.setTime(today.getTime() + 4 * 60 * 60 * 1000)

console.log(today)
// Sat Sep 10 2022 11:24:04 GMT+0500 (Pakistan Standard Time)

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 as input representing the milliseconds since January 1st, 1970, at 00:00:00 UTC and sets the value on the given date.

We multiplied the number of hours by 60 * 60 * 1000 to convert them to milliseconds before passing the value to the setTime() method.

The above methods also take care of the scenario where adding a specific number of hours to date results in the next day, month, or year:

const date = new Date('2022-09-10T16:23:23.900Z')

// Add 10 hours
date.setTime(date.getTime() + 10 * 60 * 60 * 1000)

console.log(date.toUTCString())
// Sun, 11 Sep 2022 02:23:23 GMT

You can also add a method to the Date's prototype that adds the given number of hours to the current date:

Date.prototype.addHours = function (hours) {
  const date = new Date(this.valueOf())
  date.setTime(date.getTime() + hours * 60 * 60 * 1000)
  return date
}

const date = new Date('2022-09-10T16:23:23.900Z')

// Add 12 Hours
const result = date.addHours(12)

console.log(result.toUTCString())
// Sun, 11 Sep 2022 04:23:23 GMT

How to add hours to a date in JavaScript | Coding Tips And Tricks

Are we missing something?  Help us improve this article. Reach out to us.

Are you looking for other code tips?

Check out what's on in the category: javascript, programming
Check out what's on in the tag: javascript, programming