Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the number of months between two dates in C#

Tags:

c#-4.0

I am doing this

datediff = (date1 - DateOfDeposit).TotalDays;

But this gives the no. of days and I want no.of months.

like image 338
James Avatar asked Jan 12 '23 15:01

James


2 Answers

The simplest option is probably to use my Noda Time library, which was designed for exactly this sort of thing (as well as making it cleaner to work with dates and times in general):

LocalDate start = new LocalDate(2013, 1, 5);
LocalDate end = new LocalDate(2014, 6, 1);
Period period = Period.Between(start, end, PeriodUnits.Months);
Console.WriteLine(period.Months); // 16

There's nothing built into .NET to make this particularly easy. You could subtract years and months as per Ani's answer, but then also take the day of month into account to avoid the issue I describe in comments. I'd suggest writing a good set of unit tests first though - bearing in mind leap years and the like.

like image 101
Jon Skeet Avatar answered Jan 16 '23 17:01

Jon Skeet


Assuming you want the number of whole months, I think this should work (not sure what corner-cases this doesn't handle, but can't think of any off the top of my head):

12 * (date1.Year - DateOfDeposit.Year) + (date1.Month - DateOfDeposit.Month)

You could always add any fractional component with DateTime.Day, but it's not clear how that should precisely be defined (how many months are between Jan 29 and Feb 27?).

If you're doing a lot of date-time handling, Jon Skeet's Noda Time library (that he mentions in his answer) is a good choice.

like image 43
Ani Avatar answered Jan 16 '23 19:01

Ani