How to calculate the difference in months between two dates in C#?
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. The documentation says that I can use TimeSpan
like:
TimeSpan 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?
Here is a comprehensive solution to return a
DateTimeSpan
, similar to aTimeSpan
, except that it includes all the date components in addition to the time components.Usage:
Outputs:
For convenience, I've lumped the logic into the
DateTimeSpan
struct, but you may move the methodCompareDates
wherever you see fit. Also note, it doesn't matter which date comes before the other.This worked for what I needed it for. The day of month didn't matter in my case because it always happens to be the last day of the month.
Use Noda Time:
(example source)
You can use the DateDiff class of the Time Period Library for .NET:
You can have a function something like this.
For Example, from 2012/12/27 to 2012/12/29 becomes 3 days. Likewise, from 2012/12/15 to 2013/01/15 becomes 2 months, because up to 2013/01/14 it's 1 month. from 15th it's 2nd month started.
You can remove the "=" in the second if condition, if you do not want to include both days in the calculation. i.e, from 2012/12/15 to 2013/01/15 is 1 month.