Wrong date calculation

4

I have the following method:

TimeSpan dt = dataFinal.Subtract(dataInicial);

double anos = Math.Floor(dt.Days / 365.25);
double meses = Math.Floor(((dt.Days - anos * 365.25) / 30));

return string.Format("{0} Anos e {1} mês(es)", anos, meses);

It receives a date and calculates the time between the two dates. But if I pass by example:

DataIncial -> 11/03/1992
dataFinal -> 11/03/2015

It should return me 23 anos e 0 mes(es) , but it is returning 22 anos e 12 mes(es) .

How can I fix this?

    
asked by anonymous 11.03.2015 / 15:38

2 answers

7

Alternatively you can use a library that can properly handle this as Jon Skeet's Noda Time (I wanted it to become official the. Net). He already gave an example doing this in this answer :

var start = new LocalDateTime(2014, 1, 1, 8, 30);
var end = new LocalDateTime(2014, 9, 16, 12, 0);
Period delay = new PeriodBuilder { 
        Months = 8, 
        Days = 10,
        Hours = 2,
        Minutes = 20
    }
    .Build();
Period difference = (Period.Between(start, end) - delay).Normalize();

Why is this a good alternative? Because she thought of everything. The way the question is being asked is naive and disregarding, for example, that months have different days and leap years in the correct way (even if it appears to be). If you want a real and not approximate solution, then do it the right way. In the current form several moments will give wrong results, although the majority can hit. But it's a coincidence. As they say, even a stopped clock will set the correct time twice a day.

You can write your own code to handle this but it is not the focus of the question and I would probably forget about some point and the algorithm would not be reliable.

    
11.03.2015 / 16:36
2

You can correct this by checking the meses variable before printing.

if(meses == 12) {
  meses = 0;
  anos++;
}

return string.Format("{0} Anos e {1} mês(es)", anos, meses);
    
11.03.2015 / 15:43