As we know, JavaScript's Date object does not have any additional or subtract function for performing calculations between two date objects. Therefore, I have simply written a function that can do this:
<!DOCTYPE html>
<html>
<head>
<title>Adding hours-JavaScript</title>
</head>
<body>
<script>
Date.prototype.addHours = function (h) {
this.setTime(this.getTime() + (h * 60 * 60 * 1000));
return this;
}
//to test this function c
document.write(new Date().addHours(4));
</script>
</body>
</html>
<!DOCTYPE html> <html> <head> <title>Adding hours-JavaScript</title> </head> <body> <script> var currentdate = new Date(); currentdate.setMinutes(currentdate.getMinutes() + 20); alert(currentdate); </script> </body> </html>
Instantiating a Date Object:
var currentdate = new Date();: This line creates a new Date object named currentdate, representing the current date and time when the script is executed.
Adding Minutes:
currentdate.setMinutes(currentdate.getMinutes() + 20);: Here, the setMinutes() method is used to add 20 minutes to the current time stored in the currentdate object. It retrieves the current minutes using currentdate.getMinutes(), adds 20 to it, and then updates the minutes value of the currentdate object.
Displaying the Result:
alert(currentdate);: This line displays an alert dialog containing the updated value of currentdate, which now represents the current date and time 20 minutes ahead of the original time.
Now we can easily able Add hours to JavaScript Date object using above two function.Let take some exmaple.
var currentdate = new Date();
currentdate.setMinutes(currentdate.getMinutes() + 20);
alert(currentdate);
var currentdate = new Date();
currentdate.setMinutes(currentdate.getMinutes() + 5);
alert(currentdate);
var currentdate = new Date();
currentdate.setMinutes(currentdate.getMinutes() + 30);
alert(currentdate);