As we know that JavaScript’s Date object does not have any additional or subtract function for performing calculation between two date objects.So that 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

Using .getMinutes() to get the current minutes of Date Object ,then add minutes and use .setMinutes() to update the current  date object.
<!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>

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);

The post [Solved]-How to add minutes in Date Object using javascript appeared first on Software Development | Programming Tutorials.



Read More Articles