Blog

Adding number of days to an entered date in Javascript

Posted by : Leo T Abraham on 6 July, 2013

In the given piece of code what I have done is: Using one textbox the date is accepted and 3 days are add to the entered date. Using this code you can easily add any number of days to the entered date.

<html>
<head>
</head>
<body>
    <br>
    <h1>Change Date in Old Date and Click outside the textbox to increase the old date by 3</h1>
    Old Date (MM/DD/YYYY) : <input type="text" id="date1" onChange="datechange()"/><br><br>
    New Date (MM/DD/YYYY) : <input type="text" id="date2"/>
<script>
    function datechange()
    {
        var d = 3;
        var myDate=new Date(document.getElementById('date1').value);
        myDate.setDate(myDate.getDate()+parseInt(d));
        document.getElementById('date2').value = (myDate.getMonth()+1)+'/'+(myDate.getDate())+'/'+(myDate.getFullYear());
    }
</script>
</body>
</html>

user image
Matt Johnson
This approach will only work if the browser uses mm/dd/yyyy format. Much of the world uses dd/mm/yyyy format, and others use yyyy.mm.dd or other formats. Have you looked into moment.js?
user image
Aravind
Thanks machaaa.....
user image
Ajeesh A
Its working.. Thanks... Leo