How to Add Hours to a Date Object in JavaScript

by Matt Heff
5 read

As if programming and dealing with dates did not have enough headaches that come from timezones, daylight savings, leap years the JavaScript Date API does not offer us a way to add hours to Date objects.

Fortunately with this tutorial we are going to do this ourselves and do it a couple of ways.

Method 1: Create a function ( use Date.setHours() )

function addHours(dateObj, hours){
   //We create a new Date Object so that we dont alter the one passed into the function (this is a pure function )
   const dateUpdated = new Date(dateObj.getTime());
   dateUpdated.setHours( dateUpdated.getHours() + hours);
   return dateUpdated;

const dateDemo = new Date('2022-06-22T12:00:00.000Z'); 
console.log(dateDemo); //2022-06-22T12:00:00.000Z

let dateModified = addHours(dateDemo,1)
console.log(dateModified); //2022-06-22T13:00:00.000Z

dateModified = addHours(dateDemo,3); //Original Date is not modified
console.log(dateModified); //2022-06-22T15:00:00.000Z

dateModified = addHours(dateModified,3)
console.log(dateModified); //2022-06-22T18:00:00.000Z

In the above function we create the variable dateUpdated and create a new Date Object so that the dateObj that is passed does not get modified. The Date.setHours() function updates the object, the above implementation is a pure state function, this will help prevent unexpected behaviours.

Method 2: Use NPM Package date-fns

If you are inclined to use NPM packages then this is a great one to make dates a little nicer in JavaScript or NodeJS

So this assumes you have NodeJS installed or an IDE where you can install NPM packages, you can install the package via the command below. We are only going to focus on demonstrating the addHours functionality.

npm install date-fns

import { addHours } from 'date-fns';

const date = new Date('2022-06-22T12:00:00.000Z');

//Add 1 hour to the existing date
let newDate = addHours(date, 1);
console.log(newDate); // 2022-06-22T13:00:00.000Z

//Add 2 hour to the already updated date
newDate = addHours(newDate, 2);
console.log(newDate); // 2022-06-22T15:00:00.000Z

//Original Date Object has not been modified
console.log(date); // 2022-05-15T12:00:00.000Z

The NPM package offers loads of date functions if you are in a situation to use this i would recommend it, anything that makes our lives easier with dates is worthwhile!

A few examples of date-fns functions


Code Repo

Github: Example 1

Github: Example 2

Related Posts