Adding two periods on nodatime

Where listObjAge is a list with multiple periods;

Period objTotalPeriod = listObjAge[0].period;
for (int i = 1; i < listObjAge.Count; i++) {
   objTotalPeriod += listObjAge[i].period;
}

In-short:
What i am getting:

listObjAge[0].period + listObjAge[1].period = ????.
2 yr 1 mnth 28 days  + 0 yr 8 mnth 30 days  = 2 yr 9 mnth 58 days 
// this result is not wrong but is there any way to correctly add days for the above code.

What i am expecting:

2 yr 1 mnth 28 days  + 0 yr 8 mnth 30 days  = 2 yr 10 mnth 28 days 

As you can see i want to add results of two period. Is there any way we can achieve it using nodatime.

Solved:
I know its not correct theoretically. But it worked for me.

int intDays = 0;
for (int i = 0; i < listObjAge.Count; i++) {
     intDays += listObjAge[i].period.Days; // adding all the days for every period
}

strYear = (intDays / 365).ToString();
strMonth = ((intDays % 365) / 30).ToString();
strDays = ((intDays % 365) % 30).ToString();
Jon Skeet
people
quotationmark

It sounds like you're looking for something to normalize the months and days (and weeks?). The existing Normalize method deals with everything from "days downwards" (e.g. hours) so you can use that to start with:

public static Period NormalizeIncludingMonths(this Period period, int daysPerMonth)
{
    period = period.Normalize();
    int extraMonths = days / daysPerMonth;
    int months = period.Months + extraMonths;
    int extraYears = months / 12;
    // Simplest way of changing just a few parts...
    var builder = period.ToBuilder();
    builder.Years += extraYears;
    builder.Months = months % 12;
    builder.Days = days % daysPerMonth;
    return builder.Build();
}

So in your case, it sounds like you might want:

objTotalPeriod = objTotalPeriod.NormalizeIncludingMonths(31);

Note that arithmetic using this may well produce "odd" results, just as part of the nature of calendrical arithmetic.

people

See more on this question at Stackoverflow