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
- [Solve] Azure "Windows logins are not supported in this version of SQL Server"
- Household Electricity Consumption Calculator
- How to call stored procedure in Entity Framework Core with parameters
- [Fixed] FileSystemException: Cannot retrieve length of file, path ='...' (OS Error: No such file or directory, errno = 2)
- [Simple Trick]-How To Comment And Uncomment Blocks Of Code In The VBA Editor
- [Solved]-"error obtaining vcs status: exit status 128 use -buildvcs=false to disable vcs stamping."
- [Fixed]-npm warn deprecated [email protected]: this version of tar is no longer supported, and will not receive security updates. please upgrade asap.