Difference between Dates JS - Error momentjs

2

I need to calculate the difference between two reported dates. I need to know the result in years and months. I used the momentary library in conjunction with angularjs.

By putting the Start date as 06/07/2015 and the date of birth as 06/07/1957, the expected result would be 58 years 0 months and 0 days. But the result was 58 years 0 months and 6 days

The function in JS that does this conversion is as follows:

function converterData(){

    var hoje = moment($scope.final, "DD/MM/YYYY");
    var dia  = moment($scope.nascimento, "DD/MM/YYYY");
    var duracao = moment.duration(hoje.valueOf()- dia.valueOf(), 'milliseconds');
                    $scope.idadeAnos =  duracao.years();
                    $scope.idadeMeses =  duracao.months();
                    $scope.idadeDias = duracao.days();
}

I could not find the error!

    
asked by anonymous 06.07.2015 / 18:04

1 answer

2

To calculate the difference between a large time interval, calculate the years, months, and days separately.

Using milliseconds to calculate a difference of months will hardly bring the expected result, as the moment will assume that every month has 30 days.

Example with the date given in the question:

var inicio = moment('1957-07-06');
var agora = moment('2015-07-06');

var diferenca = moment.duration({
    years: agora.year() - inicio.year(),
    months: agora.month() - inicio.month(),
    days: agora.date() - inicio.date()
});

document.getElementById("anos").innerHTML = diferenca.years() + ' ano(s)';
document.getElementById("meses").innerHTML = diferenca.months() + ' mes(es)';
document.getElementById("dias").innerHTML = diferenca.days() + ' dia(s)';
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
<p>Se passaram <b id="anos"></b>, <b id="meses"></b> e <b id="dias"></b>.</p>
    
07.07.2015 / 04:46