This post will describe the process to add hours to a date object in JavaScript.
How to Add Hours to Date Object in JavaScript?
For adding hours to a Date object, use the given below JavaScript predefined methods:
- getTime() method
- setHours() method
Let’s look at the working of the above-mentioned methods.
Method 1: Add Hours to Date Object Using getTime() Method
To add hours to the Date object, the “getTime()” method is used. It represents the time for the given date in universal time. It returns time in milliseconds:
Syntax
Use the following syntax for the getTime() method:
Example
Create a new date object and store it in a variable “date”:
In order to add hours to a date object, define a function “addHoursToDate()” with a parameter “hour”, call the ”setTime()” method of date object then first obtain the current time using the “getTime()” method, and then, add hours’ of milliseconds to it:
date.setTime(date.getTime() + hour * 60 * 60 * 1000);
return date;
}
Print today’s date using “console.log()” method:
Call the function “addHoursToDate()” by passing “2” hours:
Print the new date and time by adding 2 hours in it on the console:
The corresponding output will be:
Method 2: Add Hours to Date Object Using setHour() Method
There is another Date object’s method “setHour()” used for adding hours to date. It sets the hours for a date according to local time.
Syntax
For setHours() method, use the given syntax:
In the above syntax:
- “hours” indicates an integer number between 0 and 23.
- “min” represents minutes between 0 and 59.
- “sec” is the seconds between 0 and 59.
- “ms” is the milliseconds between 0 and 999.
- The “min, sec, and ms” are optional parameters but linked with one another, if use “ms”, then it is mandatory to use “sec” and “min”.
Example
In order to add hours to a date object, define a function “addHoursToDate()” with a parameter “hour”, and get the value of hours by passing a number as an argument in the “setHours()” method:
date.setHours(hour);
}
Call the function “addHoursToDate()” by passing “2” hours to add in the date:
Print the new date and time by adding 2 hours in it on the console using “console.log()” method:
Output
Conclusion
To add hours to a date object, use the JavaScript Date object’s predefined methods including “getTime()” method or “setHours()” method. The setHours() method sets the hours in date according to local time while the getTime() method returns time in milliseconds and represents the time in universal time. This post described the process for adding hours to a date object in JavaScript.