Jquery DatePicker

0

Greetings. I am using this plugin and it has worked very well, but I need to be able to subtract 2 dates (start - end) to show the result in days in a span. How could I perform this operation? Does this plugin have any method to do this? This is the way I add the dates.

$("#fechainicio").datepicker();
$("#fechafin").datepicker(); 
    
asked by Alex Hunter 12.12.2017 в 19:13
source

2 answers

3

To calculate the number of days between two dates I would do the following:

$("#fechaInicio").datepicker();
$("#fechaFin").datepicker(); 

$("#restar").click(function(){
    var fechaInicio = new Date($("#fechaInicio").val());
    var fechaFin = new Date($("#fechaFin").val());

    var diaEnMils = 1000 * 60 * 60 * 24;

    var resultado = (fechaFin.getTime() - fechaInicio.getTime()) / diaEnMils;

    console.log('Entre las dos fechas hay ' + resultado + ' días');
});
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

<p>Fecha inicio: <input type="text" id="fechaInicio"></p>
<p>Fecha fin: <input type="text" id="fechaFin"></p>

<button id="restar">Restar fechas</button>

EXPLANATION:

Basically we are obtaining the amount of milliseconds that there are in each date, we subtract the milliseconds and finally we convert them to days.

    
answered by 12.12.2017 / 19:50
source
0

I use this function to make the difference in days of 2 dates given.

$("#restar").click(function(){
        var startDt=document.getElementById("datepicker").value;
        var endDt=document.getElementById("datepicker2").value;

        console.log(restaFechas(startDt,endDt));
    });




   function restaFechas(f1,f2){
   var aFecha1 = f1.split('/'); 
   var aFecha2 = f2.split('/'); 
   var fFecha1 = Date.UTC(aFecha1[2],aFecha1[1]-1,aFecha1[0]); 
   var fFecha2 = Date.UTC(aFecha2[2],aFecha2[1]-1,aFecha2[0]); 
   var dif = fFecha2 - fFecha1;
   var dias = Math.floor(dif / (1000 * 60 * 60 * 24)); 
   return dias;
   }

Greetings.

    
answered by 12.12.2017 в 19:41