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
To be able to calculate the difference between 2 dates in months is a perfectly logical thing to do, and is needed in many business applications. The several coders here who have provided comments such as - what's the difference in months between "May 1,2010" and "June 16,2010, what's the difference in months between 31 December 2010 and 1 Jan 2011? -- have failed to understand the very basics of business applications.
Here is the answer to the above 2 comments - The number of months between 1-may-2010 and 16-jun-2010 is 1 month, the number of months between 31-dec-2010 and 1-jan-2011 is 0. It would be very foolish to calculate them as 1.5 months and 1 second, as the coders above have suggested.
People who have worked on credit card, mortgage processing, tax processing, rent processing, monthly interest calculations and a vast variety of other business solutions would agree.
Problem is that such a function is not included in C# or VB.NET for that matter. Datediff only takes into account years or the month component, so is actually useless.
Here are some real-life examples of where you need to and correctly can calculate months:
You lived in a short-term rental from 18-feb to 23-aug. How many months did you stay there? The answer is a simple - 6 months
You have a bank acount where interest is calculated and paid at the end of every month. You deposit money on 10-jun and take it out 29-oct (same year). How many months do you get interest for? Very simple answer- 4 months (again the extra days do not matter)
In business applications, most of the time, when you need to calculate months, it is because you need to know 'full' months based on how humans calculate time; not based on some abstract/irrelevant thoughts.