convert mm/dd/yyyy to dd/mm/yyyy using javascript while adding Number of days with a Date [duplicate]

StackOverflow https://stackoverflow.com/questions/21598289

  •  07-10-2022
  •  | 
  •  

Question

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

Was it helpful?

Solution

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();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top