# calculate number of months between two date

I am trying to calculate the number of months between two dates in c#.
I have two dates in a c# string.
At first i was calculating Mat.Abs(DateTime.Parse(txtStartDt.Value).Month - DateTime.Parse(txtEndDt.Value).Month))+ 1

Then i realized that i may have values where the years differ eg. 2007 - 2009 the code i have above doesnt account for that.

What would be the best solution/algorithm to get the correct number of months from two dates?
###### Who is Participating?

Senior DBACommented:
You could also just do something like this:

(txtEndDt.Yr * 12 + txtEndDt.Mth) - (txtStartDt.Yr * 12 + txtStartDt.Mth)

Naturally you would have to convert the text to numeric (I'm not sure how to do that, but I'm guessing you know that already :-) ) .
That's such a simple calc the overhead should be very low.
0

Commented:
The DateDiff function will return the number of month boundaries between 2 dates.

If you are running it in SQL Server, the syntax is:

SELECT DATEDIFF(month, @StartDate, @EndDate)

No idea if C# has an analogous function.
0

Commented:
If you just need the value, there is a function called the DateDiff method.  Need to import the Microsoft.VisualBasic namespace, though, which is rather fat if you're going for a thin load.

If you actually have to show the code to have it done, for a school project, or so, see the code:

Cheers,
Justicator
``````using System;

using System.Collections.Generic;

using System.Text;

namespace Console_DateTime

{

class Program

{

static void Main(string[] args)

{

System.DateTime dtTodayNoon = new System.DateTime(2006, 9, 13, 12, 0, 0);

System.DateTime dtYestMidnight = new System.DateTime(2006, 9, 12, 0, 0, 0);

System.TimeSpan diffResult = dtTodayNoon - dtYestMidnight;

Console.WriteLine("Yesterday Midnight - Today Noon = " + diffResult.Days);

Console.WriteLine("Yesterday Midnight - Today Noon = " + diffResult.TotalDays);

}

}

}
``````
0

RetiredCommented:
Hi joan2006;

I would suggest that you use the Visual Basic function to get the needed result. This function will take care of leap year and between to years. In order to use the Visual Basic function in a C# application you can do the following:

1. Add a DLL reference Microsoft.VisualBasic to the application
found in the .Net Table of the Add Reference dialog box.
2. Add a using statement, using Microsoft.VisualBasic.

Fernando
``````using Microsoft.VisualBasic;

DateTime firstDate = DateTime.Parse("11/02/2008");
DateTime secondDate = DateTime.Parse("02/14/2009");

long noOfMonths = DateAndTime.DateDiff(DateInterval.Month,
firstDate, secondDate, FirstDayOfWeek.Sunday, FirstWeekOfYear.Jan1);

MessageBox.Show("Number of Months = " + noOfMonths.ToString());
``````
0

RetiredCommented:
Sorry type O in this line.

1. Add a DLL reference Microsoft.VisualBasic to the application
found in the .Net Tab of the Add Reference dialog box.
0