How to calculate the difference of days using input of type "date"? [duplicate]

3

My question is this:

I have two input of type date .

What I want to do in Javascript is to calculate the difference of days from first to second, that is, if the person put on 09/19/2015 on the first input and on 25/09/2015 on the second, then it is calculated how many days have passed from 19 to 25, that is, 6 days.

How will I do this?

Thank you.

    
asked by anonymous 19.09.2015 / 02:39

1 answer

4

You can use the method below for this, remembering that you can add some checks such as: If the start date is less than the end date or if the values are filled in.

function calculaDiferenca(dataInicial, dataFinal) {

    /*gera um objeto do tipo Date com valor do input*/
    var date1 = new Date(dataInicial);        
    var date2 = new Date(dataFinal);

    console.log(date2.getTime());
    /*Subtrai a segunda data em milisegundos pela primeira e usa função abs para retornar o valor absoluto*/
    var timeDiff = Math.abs(date2.getTime() - date1.getTime());

    /*agora ele divide o valor da diferença das datas em milisegundos pela quantidade de milisegundos em um dia e usa ceil para 
    retorna o menor número inteiro*/
    var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));

    alert(diffDays + ' dias');
}

Follow jsfiddle .

    
19.09.2015 / 03:01