JavaScript Date Add Hours


Working with dates in JavaScript often involves manipulating them by adding or subtracting time units.

Adding hours to a date object is a common operation when dealing with time-based calculations or scheduling tasks.

In this tutorial, we'll explore various methods to add hours to a JavaScript Date object.

    Table of Contents

  1. Using setHours() Method
  2. Using getTime() and setTime() Methods
  3. Using the Date Constructor
  4. Using Libraries like date-fns or moment.js
  5. Conclusion

1. Using setHours() Method

The setHours() method sets the hour of a date object to a specified value.

The idea is to get the current hour of the date object and add the specified number of hours to it.

Let's see an example to add 5 hours to the current date object.

Example

let date = new Date();
console.log(date);

// 👉️ adding 5 hours to the current date
date.setHours(date.getHours() + 5);

console.log(date);

2. Using getTime() and setTime() Methods

Another approach involves converting the date to milliseconds using getTime(), then adding the required hours in milliseconds, and finally setting the updated time using setTime().

Milliseconds can be converted to hours by dividing it by 3600000 (60 * 60 * 1000).

Example

let date = new Date();
console.log(date);

// 👉️ adding 5 hours to the current date
date.setTime(date.getTime() + (5 * 60 * 60 * 1000));
console.log(date);

3. Using the Date Constructor

You can also add hours by creating a new Date object with the sum of the current time and the specified hours.

Example

let date = new Date();
console.log(date);

// 👉️ adding 5 hours to the current date
date = new Date(date.getTime() + (5 * 60 * 60 * 1000));
console.log(date);

4. Using Libraries like date-fns or moment.js

Third party libraries like date-fns or moment.js provide direct methods to add hours to a date object.

You need to install these libraries using npm or yarn before using them in your project.

Using date-fns

The addHours() method of date-fns adds the specified number of hours to a date object.

var { addHours } = require('date-fns');

let date = new Date();

// 👉️ adding 5 hours to the current date
date = addHours(date, 5);
console.log(date);

Using moment.js

The add() method of moment.js is used to add time units to a date object. It takes two arguments, the first one is the number of units to add and the second one is the unit of time.

let moment = require('moment');

let date = new Date();

// 👉️ adding 5 hours to the current date
date = moment(date).add(5, "hours").toDate();
console.log(date);

Conclusion

Adding hours to a JavaScript Date object can be achieved through various methods. Whether using native JavaScript methods like setHours() and getTime() with setTime() or leveraging third-party libraries like date-fns or moment.js.