How do I find difference in MONTH for two DataTime

  • Thread starter Thread starter Ali Baba
  • Start date Start date
A

Ali Baba

Hi,

Is there is equivalent of VB's DateDiff() method in C#. I need to find
difference in months between two dates that are years apart. Docs says
that I can use TimeSpan like:

TimeSpam ts = date1 - date2;

but this gives me data in Days. I don't want to divide this number by 30
because not every month is 30 days and since the two operand values are
quite apart from each other, I am afraid dividing by 30 might give me a
wrong value.

Any suggestions???
 
Ali,

You can call the DateDiff function in VB. Add a reference to
Microsoft.VisualBasic.dll. Once you do that, you can call the static
DateDiff method on the DateAndTime class in the Microsoft.VisualBasic
namespace.

Hope this helps.
 
The VisualBasic.dll's date functions may be suited for
doing what you require relatively quickly, but its
probably just as easy to write your own. I haven't
tested this, but I have a feeling all you need is
something like this:

int monthsApart = 12*(date2.Year-date1.Year) +
date2.Month-date1.Month;

01/01/00 - 01/01/03 = 36 months apart
12/01/00 - 01/01/03 = 25 months apart
01/01/00 - 06/01/99 = -7 months apart


Jerry Negrelli
Senior Software Engineer
Data Scientific Corporation
 
Nicholas,

This is a good idea. However, what affect is this going to have on my
deployment?
 
Ali,

None, Microsoft.VisualBasic.dll is distributed with the .NET framework.
 
Try This:

public int MONTH = 1;
public int YEAR = 2;
public int DAY = 3;

public int dateDiff(int interval, DateTime d1, DateTime d2){
if(d1 < d2){
//Swap the operators and then return.
//I expect the larger date to appear first
return dateDiff(interval, d2, d1);
}
years = d1.Year - d2.Year;
months = d1.Month - d2.Month;

if(interval == MONTH){
return (years * 12) + months;
}

if(interval == YEAR){
return years;
}
return ts.Days;
}
 
Back
Top