You are currently viewing Easy Ways to Add Hours to Date in JavaScript

Easy Ways to Add Hours to Date in JavaScript

JavaScript Add Hours to Date

In this article, we’re going to see how to add hours to date in javascript.  It’s very simple, you need to have a date with the JS pattern that is created by Date() object, like:
const newDate = new Date();
console.log(newDate)
This Date() object returns the current date and time of the user in timestamp format
javascript add hours to date
If you see the output, we have a date and we need to add some hours to it. Let’s see how can do it.
The date is an object from the date class, so we have access to the ‘getHours()’ method to get the hours of this date.
console.log(newDate.getHours());   //18
So, we can use the “setHours()” method to add the hours to date in javascript.  Here, we need to know the current hours because if we pass 3 to the “setHours” method, it returns 3 hours without adding 3 from the current hours.
newDate.setHours(3)
console.log(newDate)
using setHours() method to add hours
So, to get current hours with the ‘getHours’ and add the hours that we want to add. If we add 3 hours to our current time, we have the hours 18 + 3 =21 hours, because the current hour is 18 and our added time is 3.
newDate.setHours(newDate.getHours() + 3)
console.log(newDate)
using getHours() and setHours() methods to add hours
We can add hours by using getTime() method:
returns the number of milliseconds since January 1, 1970, which is commonly referred to as the Unix timestamp. By adding the desired number of hours in milliseconds to the current timestamp and creating a new date object from it, we can achieve the desired result.
const currentDate = new Date();
const hoursToAdd = 3;
const newDate = new Date(currentDate.getTime() + hoursToAdd * 60 * 60 * 1000);
console.log(newDate);

using getTime() method to add hours

Leave a Reply