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:
Approach-1
<!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>
Approach-2
<!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.
- How to add 20 minutes to a current date?
var currentdate = new Date();
currentdate.setMinutes(currentdate.getMinutes() + 20);
alert(currentdate);
- Add 5 minutes to current time javascript
var currentdate = new Date();
currentdate.setMinutes(currentdate.getMinutes() + 5);
alert(currentdate);
- How to add 30 minutes to a JavaScript Date object?
var currentdate = new Date();
currentdate.setMinutes(currentdate.getMinutes() + 30);
alert(currentdate);
Read Similar Articles
- Download sample 3g2 File For Testing
- Include with FromSqlRaw and stored procedure in EF Core
- Solved : Failed to Complete negotiation With the Server In Angular SignalR Using Core
- Ceiling Fan Power Consumption Calculator | How Much Power Does a Fan Use
- Solve missing Java EE Server Libraries Error in Netbeans