In C#/.NET TimeSpan
has TotalDays
, TotalMinutes
, etc. but I can't figure out a formula for total months difference. Variable days per month and leap years keep throwing me off. How can I get TotalMonths?
Edit Sorry for not being more clear: I know I can't actually get this from TimeSpan
but I thought using TotalDays
and TotalMinutes
would be a good example to express what I was looking for ... except I'm trying to get Total Months.
Example: Dec 25, 2009 - Oct 6, 2009 = 2 TotalMonths. Oct 6th to Nov 5th equals 0 months. On Nov 6th, 1 month. On Dec 6th, 2 months
(I realize this is an old question, but...)
This is relatively painful to do in pure .NET. I'd recommend my own Noda Time library, which is particularly designed for things like this:
LocalDate start = new LocalDate(2009, 10, 6);
LocalDate end = new LocalDate(2009, 12, 25);
Period period = Period.Between(start, end);
int months = period.Months;
(There are other options, e.g. if you only want a count of months even across years, you'd use Period period = Period.Between(start, end, PeriodUnits.Months);
)
See more on this question at Stackoverflow