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?
Expanded Kirks struct with ToString(format) and Duration(long ms)
This is in response to Kirk Woll's answer. I don't have enough reputation points to reply to a comment yet...
I liked Kirk's solution and was going to shamelessly rip it off and use it in my code, but when I looked through it I realized it's way too complicated. Unnecessary switching and looping, and a public constructor that is pointless to use.
Here's my rewrite:
Usage1, pretty much the same:
Usage2, similar:
you can use the following extension: Code
Implementation !
Here's how we approach this:
If you want the exact number of full months, always positive (2000-01-15, 2000-02-14 returns 0), considering a full month is when you reach the same day the next month (something like the age calculation)
Edit reason: the old code was not correct in some cases like :