Difference between JS Dates - Error momentjs

Asked

Viewed 1,183 times

2

I need to calculate the difference between two dates reported. I need to know the results in years and months and days. I used the momentjs library in conjunction with Angularjs.

By setting 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 JS function 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 couldn’t find the mistake!

  • what is the result of hoje.valueOf() and of dia.valueOf()?

  • end: 1436151600000 birth: -394146000000

  • You can see a different result on this site:http://www.profcardy.com/calculated/applicationsphp?calc=5

  • Dude, I ran some tests, and although I couldn’t identify why, I saw that the problem occurs when you try to make a difference with the day beating. A workaround would you add a day in hoje, take the duration and, before passing the duration values, do duracao = duracao.subtract(1,'days') (is ugly, but it was the alternative I thought)

1 answer

3

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

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

Example with date provided in 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>

  • 1

    this solution is partial because if you put the following dates: start 05/07/1957 and end 06/06/2015, the day will be -1

  • 1

    updated response. Moment.js should treat dates so this doesn’t happen, but it has an open bug that prevents this from happening in the case of negative days.

  • Opa the bug has been fixed: https://github.com/ichernev/moment/commit/e3ec1957353406b97562b4585232705651358169, now just wait for merge and release :-)

Browser other questions tagged

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