I have problems with NodaTime lib. My goal: calculate Year / Month / Date between two dates. So here is my test case:
private static void Main()
{
var list = new List<Tuple<DateTime, DateTime>>
{
new Tuple<DateTime, DateTime>(new DateTime(1980, 1, 1), new DateTime(1983, 12, 31)),
new Tuple<DateTime, DateTime>(new DateTime(2009, 1, 1), new DateTime(2015, 01, 23))
};
var totalPeriod = Period.Zero;
foreach (var tuple in list)
{
var dateFrom = tuple.Item1;
var dateTo = tuple.Item2;
var ld1 = new LocalDate(dateFrom.Year, dateFrom.Month, dateFrom.Day);
var ld2 = new LocalDate(dateTo.Year, dateTo.Month, dateTo.Day);
var period = Period.Between(ld1, ld2, PeriodUnits.YearMonthDay);
totalPeriod += period;
}
Console.WriteLine("Years: {0}, Months: {1}, Days: {2}",
totalPeriod.Years,
totalPeriod.Months,
totalPeriod.Days);
Console.Read();
}
Yield:
Years: 9, Months: 11, Days: 52
This is wrong for me. I want to get, for example, the following result (of course, the output depends on the number of days in a month, assuming that there are 31 days in our month):
Years: 10, Months: 0, Days: 21
So, I want the days to be rounded to a few years and a month. How can i get this?
Answer:
Using Matt's answer, I created the following solution:
foreach (var tuple in list)
{
var dateFrom = tuple.Item1;
var dateTo = tuple.Item2;
var period = Period.Between(LocalDateTime.FromDateTime(dateFrom).Date, LocalDateTime.FromDateTime(dateTo).Date, PeriodUnits.YearMonthDay);
totalPeriod += period;
}
while(totalPeriod.Days >= 30)
{
totalPeriod = totalPeriod - Period.FromDays(30);
totalPeriod = totalPeriod + Period.FromMonths(1);
while (totalPeriod.Months >= 12)
{
totalPeriod = totalPeriod - Period.FromMonths(12);
totalPeriod = totalPeriod + Period.FromYears(1);
}
}