Blog

Adding number of days to current date in Javascript dynamically

Posted by : Leo T Abraham on 8 August, 2013

Here what we are doing is: Setting curent date to a textbox and making it readonly. Then we allow user to enter the number of days to be added to the current date. On change event, the number of  days entered is added to the current date. Try out the following code to see its working.

<html>
       <head>
             <title>Adding number of days to current date in Javascript</title>
       </head>
       <body onload="addDate();">
             <br/>
            <h1>Adding number of days to current date in Javascript</h1>
            Today's Date (MM / DD / YYYY) : <input type="text" id="date1" readonly/> <br/> <br/>
            Number of days to add : <input type="text" id="days" onChange="datechange()" /> <br/> <br/>
            New Date (MM / DD / YYYY) : <input type="text" id="date2"
readonly/>
            <script type="text/javascript">
                  function datechange()
                  {
                        var d = document.getElementById('days').value;
                        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());
                  }
                  function addDate()
                  {
                         date = new Date();
                         var month = date.getMonth()+1;
                         var day = date.getDate();
                         var year = date.getFullYear();
                         if (document.getElementById('date1').value == '')
                         {
                               document.getElementById('date1').value = day + '/' + month + '/' + year;
                         }
                  }
            </script>
      </body>
</html>

user image
DHARMENDRA KUMAYU
great !