How to add hours to a JavaScript Date object?
This is a JavaScript tutorial to show you how to add hours to JavaScript date object. To add some hours to JavaScript date object we can use setHours() method.
You can go through this tutorial if you want to know how to add minutes to date in JavaScript date object
That is very similar to this tutorial. The same type of method is used.
Here we are going to use the below JavaScript methods:
- getHours()
- setHours()
How to format javascript date to yyyy-mm-dd
how to subtract days from a date in javascript
Add Hours To Date in JavaScript Date Object
In the below example we add 5 hours to the current hour using JavaScript setHours() and getHours() method.
<!DOCTYPE html> <html> <head> <title>Title Goes Here</title> </head> <body> <script type="text/javascript"> var date1 = new Date(); date1.setHours(date1.getHours()+5); document.write(date1); </script> </body> </html>
Output:
Thu Oct 24 2018 16:14:03 GMT+0530 (India Standard Time)
The current system time was 11:14:30 and I added 5 hours to it in the above JavaScript program.
date1.setHours(date1.getHours()+hours_to_be_added);
In the above line, you have to put the hours in numeric in order to add hours to the current hour. ( put how many hours you want to add instead of hours_to_be_added )
var date1 = new Date();
In the Date() you can pass any date as a parameter. If you want to leave it system date just don’t pass anything.
History of JavaScript JavaScript is gaining popularity Day by Day
Leave a Reply