# How to add hours to a date in JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Sep 10, 2022. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-date-add-hours

> Learn how to use the getTime() and setTime() methods of date object to add hours to date in JavaScript.

To add hours to date in JavaScript:

1. Use the `getTime()` method to get the number of milliseconds since [Unix Epoch](https://attacomsian.com/blog/unix-timestamp-javacript).
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:

```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:

```javascript
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](https://attacomsian.com/blog/objects-prototypes-classes-javascript#prototypes) that adds the given number of hours to the current date:

```javascript
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
```
