Home » Javascript » How to Add Hours to a Date in JavaScript

How to Add Hours to a Date in JavaScript

In JavaScript, you can add hours using the getTime() & setTime() methods or using External Libraries (date-fns, moment.js) to update the Date object. Here’s a step-by-step guide:


Create Add Hours function

You can create a function called addHours that takes a Date object and the number of hours (N) to add as parameters. Here’s the function:


function addHours(date, hours) {
  // Get the current time in milliseconds and add N hours' worth of milliseconds
  date.setTime(date.getTime() + hours * 60 * 60 * 1000);

  // Return the updated Date object
  return date; 
}


addHours() Usage:


1) Add 24 Hours to Date

You can use the function to add hours to the current date by creating a new Date object without passing any parameters to the Date() constructor:


const currentDate = new Date();

// Add 24 hours to the current date
// e.g. current date = 2024-03-05T15:00:00.000Z
const result = addHours(currentDate, 24);

console.log(result); // Output: 2024-03-06T15:00:00.000Z


2) Adding Hours to a Specific Date

You can also add hours to a specific date by creating a Date object with a given date and time:


const date = new Date('2024-03-14T18:30:05.000Z');

// Add 2 hours to the specific date
const result = addHours(date, 2);

console.log(result); // Output: 2024-03-14T20:30:05.000Z



Explanation – getTime() & setTime()

The getTime() and setTime() are part of the Date object that is used to work with dates and times, which allows you to manipulate dates and times easily in JavaScript.

1) getTime()

This method returns the numeric value corresponding to the time for the specified date according to universal time. It returns the number of milliseconds since January 1, 1970, 00:00:00 UTC (also known as the Unix Epoch). This value is often used for comparing dates or performing date arithmetic.

example of using getTime() method

// Create a new Date object representing the current date and time
const now = new Date(); 

// Get the number of milliseconds since the Unix Epoch
const timestamp = now.getTime(); 

console.log(timestamp); 


2) setTime()

This method sets the date and time of a Date object to the specified time value, represented in milliseconds since the Unix Epoch.

example of using setTime() method

// Create a new Date object
const date = new Date(); 

// Output the current date and time
console.log(date); 

// Example timestamp representing March 5, 2021
const timestamp = 1614962400000; 

// Set the date and time of the Date object to the specified timestamp
date.setTime(timestamp); 

// Output the updated date and time
console.log(date); 


3) add ’60 * 60 * 1000′ hours (milliseconds) using setTime()

To add hours, multiply the number of hours by 60 * 60 * 1000 to convert hours to milliseconds and then add this value to the current time using setTime().

example of adding hours to a Date object

// Create a new Date object representing the current date and time
const date = new Date(); 

// Output the original date and time
console.log("Original Date:", date); 

// Number of hours to add
const hoursToAdd = 3; 

// Convert hours to milliseconds
const millisecondsPerHour = 60 * 60 * 1000; 

// Calculate total milliseconds to add
const totalMillisecondsToAdd = hoursToAdd * millisecondsPerHour; 

// Calculate the new time by adding milliseconds
const newTime = date.getTime() + totalMillisecondsToAdd; 

// Set the date and time of the Date object to the new time
date.setTime(newTime); 

// Output the updated date and time
console.log("New Date after adding", hoursToAdd, "hours:", date); 

This approach allows you to easily manipulate dates and times in JavaScript by adding or subtracting hours, minutes, seconds, etc., as needed.



Preventing Mutation

If you want to avoid mutating the original Date object, you can create a copy of the Date before applying the changes. Here’s how:


function addHours(date, hours) {
  const dateCopy = new Date(date);
  dateCopy.setTime(dateCopy.getTime() + hours * 60 * 60 * 1000);

  return dateCopy;
}



Using External Libraries

Alternatively, you can use external libraries like date-fns or moment.js to add hours to a Date.

1) date-fns – add hours


example using date-fns:


import { addHours } from 'date-fns';

const date = new Date('2024-03-14T12:30:05.000Z');

const result = addHours(date, 2);

console.log(result);


2) moment.js – add hours


example using moment.js:


import moment from 'moment';

const date = new Date('2024-03-14T12:30:05.000Z');

const result = moment(date).add(2, 'hours').toDate();

console.log(result);

Both libraries provide convenient methods for working with Dates and times.



Leave a Reply

Your email address will not be published. Required fields are marked *