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

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.