Click here to Skip to main content
15,885,914 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Find the number of months between two dates in C#
Posted
Updated 14-Dec-20 0:12am

C#
DateTime d1 = new DateTime(2020, 1, 1);
DateTime d2 = new DateTime(2020,12,31);

// subtract the dates, and divide the total days by 30.4 (avg number of days per month)
int months = (int)(Math.Floor(((d2-d1).TotalDays / 30.4)));
 
Share this answer
 
Comments
Maciej Los 18-Jun-20 2:02am    
This question is pretty old and seems OP is not interested in answer...
Nasty way but does what I need (calculate physical calender months between two dates)

//2 datetimepicker controls dtpStart & dtpEnd

DateTime sdt = dtpStart.Value;
DateTime edt = dtpEnd.Value;
int numMonths = 0;
while(sdt < edt)
{
sdt = sdt.AddMonths(1);
numMonths++;
}
 
Share this answer
 
Comments
CHill60 12-Mar-19 10:26am    
Did you read the links in Solution 1?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900