How to add two dates of type date with jquey

0

I have an input of type date, what I want is for you to take that date and add 30 days to another input date Actually I searched a lot and I have not found the solution

<input type="Date" id="FechaI" class="form-control" name="FechaI"/>
<input type="Date" id="FechaF" class="form-control" name="FechaF" />
    
asked by EDWIN ALONSO Hernandez 27.10.2017 в 02:23
source

1 answer

1

In javascript there are several libraries that would help you to do what you are looking for, however, I have created a script to explain what is to be done to add the number of days desired.

  • First you must add a function that detects when the value of the first field changes $fecha1.change(function() {} );
  • Within the function change we must convert the value of the date1 dt1 of type String to type Date . link new Date(year, month, day, hours, minutes, seconds, milliseconds);
  • After we have the date1 dt1 in Date , we proceed to add the required days and use the value to create a new date.
  • Obtained the date2 dt2 , we obtain the year, month and day with the functions getFullYear(), getMonth(), getDate()
  • Take into account that the month counts from 0 to 11, so you must add one to get the month you want.
  • $(document).ready(function() {
      var $fecha1 = $('#FechaI')
         ,$fecha2 = $('#FechaF')
            ,dias = 30;
      
      $fecha1.change(function() {
    
        var pattern = /(\d{4})-(\d{2})\-(\d{2})/
               ,dt1 = new Date(this.value.replace(pattern,'$1,$2,$3'))
               ,dt2 = new Date(dt1.setDate(dt1.getDate() + dias));
    console.log(this.value.replace(pattern,'$1-$2-$3'));
        $fecha2.val(dt2.getFullYear() + '-' + (dt2.getMonth() + 1) + '-' + dt2.getDate() );
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="Date" id="FechaI" class="form-control" name="FechaI"/>
    <input type="Date" id="FechaF" class="form-control" name="FechaF" />
        
    answered by 27.10.2017 в 05:03