How to calculate the days difference using "date" input?

Asked

Viewed 959 times

3

My question is this::

I have two input of the kind date.

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

How am I gonna do that?

Thank you.

1 answer

4


You can use the method below for this, remembering that you can add some checks like: 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');
}

Follows jsfiddle.

  • O code is not working.

  • 1

    @Gonçalo is there.. just go to fiddle http://jsfiddle.net/JS69L/751/, if you want to change something just leave in the comments =D

  • I see, in case you want to make onblour, so that as soon as you finish filling, appear an Alert with the number of days without having to click on anything as I do?

  • 1

    a yes .. 1 minute implementing explaining to you here :D

  • 1

    @Gonçalo, see if this is :D http://jsfiddle.net/buh159/JS69L/754/

  • Solved, thank you very much!

  • 1

    @Gonçalo, don’t forget to mark the answers as solved!

  • 1

    How do I mark as solved?

  • 1

    @Gonçalo, under the vote of the answer has a little arrow/checkzinho just click on it that the answer is marked as correct

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.