0

I want to add number of days with a particular date. I have done this but problem is that it works for MM/DD/YYYY format. Now i want it to work for DD/MM/YYYY format. Below is my sample code..

      <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.getDate() + 1 )  + '/' + (myDate.getMonth() + 1) + '/' + (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 = month + '/' + day + '/' + year;
              }
          }
    </script>

and the HTML code is--

   <body onload="addDate()">
         <br/>

        Number of days to add : <input type="text" id="days" onChange= "datechange()"  /> <br/> <br/>
        Today's Date (MM / DD / YYYY) : <input type="text" id="date1" onChange="datechange()" /> <br/> <br/>

        (MM / DD / YYYY) : <input type="text" id="date2" readonly/>

  </body>

Thanks in advance

rafat
  • 819
  • 2
  • 10
  • 25

1 Answers1

0

As pointed out in the comments, I think there is enough info on the duplicate questions to solve this. But in case your looking for something specific to your code sample, my suggestion is to split 'MM/DD/YYYY' by '/' and use the date objects setMonth, setDate and setFullYear methods.

function datechange() {
  var d = document.getElementById('days').value;
  var myDate = new Date();
  var d1Value = document.getElementById('date1').value;
  var ddmmyyyy = d1Value.split('/');

  myDate.setDate (ddmmyyyy[0]);  
  myDate.setMonth(ddmmyyyy[1] - 1);  // January is index 0
  myDate.setFullYear (ddmmyyyy[2]);

  myDate.setDate(myDate.getDate() + parseInt(d)); // add value of d

  document.getElementById('date2').value =  myDate.getDate() 
                                  + '/' + (myDate.getMonth() + 1)
                                  + '/' + myDate.getFullYear();
}
erickb
  • 6,193
  • 4
  • 24
  • 19
  • Thanks for your answer. But what should i do after splitting? Cause i want to add number of days with that date and can you please briefly explain? – rafat Feb 06 '14 at 09:54
  • Thank you again.What is mvDate? this mvDate is showing error – rafat Feb 06 '14 at 10:15
  • If number of days is 1 and the date is 22/2/2014 then the answer is 21/10/2014. Its not properly..Can u please help me? – rafat Feb 06 '14 at 10:23