Difference between dates

5

Whenever I move the date difference in the same month, it works, but when it is between different months, comes a negative value. How do I make a difference between dates? Look at my code. The error is in total

Code

if (($("#txtDateStart").val().split("/") == "") && ($("#txtDateEnd").val().split("/") == "")) {
    data1 = new Date();
    data2 = new Date();
}
else {
    var dtInicio = $("#txtDateStart").val().split("/");
    var dtFim = $("#txtDateEnd").val().split("/");
    data1 = new Date(dtInicio[2] + "/" + dtInicio[1] + "/" + dtInicio[0]);
    data2 = new Date(dtFim[2] + "/" + dtFim[1] + "/" + dtFim[0]);
}
var total = data2.getDate() - data1.getDate();
    
asked by anonymous 15.04.2014 / 19:35

3 answers

16

Based on one of the best OS answers in English and applied to your specific case:

if ( ($("#txtDateStart").val().split("/") == "") &&
     ($("#txtDateEnd").val().split("/") == "") ) {
   data1 = new Date();
   data2 = new Date();
}
else {
   var dtInicio = $("#txtDateStart").val().split("/");
   var dtFim = $("#txtDateEnd").val().split("/");
   data1 = new Date(dtInicio[2] + "/" + dtInicio[1] + "/" + dtInicio[0]);
   data2 = new Date(dtFim[2] + "/" + dtFim[1] + "/" + dtFim[0]);
}
var total = dateDiferencaEmDias( data1, data2 );

// a e b são objetos Date do JS
function dateDiferencaEmDias(a, b) {
   // Descartando timezone e horário de verão
   var utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
   var utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());

   return Math.floor((utc2 - utc1) / ( 1000 * 60 * 60 * 24) );
}
    
15.04.2014 / 20:03
5

Example:

date1 = new Date('2014/01/01');
date2 = new Date('2014/04/01');
var diferenca = Math.abs(date1 - date2); //diferença em milésimos e positivo
var dia = 1000*60*60*24; // milésimos de segundo correspondente a um dia
var total = Math.round(diferenca/dia); //valor total de dias arredondado 
    
15.04.2014 / 20:24
1
var total = (((Date.parse(data2)) - (Date.parse(data1))) / (24 * 60 * 60 * 1000));
    
14.09.2015 / 19:10