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?
To find the number of months or days between two dates, type into a new cell: =DATEDIF(A1,B1,”M”) for months or =DATEDIF(A1,B1,”D”) for days.
⇒ Type =INT(YEARFRAC(C4,D4)*12) & press Enter. You'll see the same result as found before. Here, we're finding out the number of years as time span first which will be shown in decimal format. Then this value will be multiplied by 12 (No.
Use the relativedelta. months + relativedelta. years * 12 formula to get the total months between two dates.
Assuming the day of the month is irrelevant (i.e. the diff between 2011.1.1 and 2010.12.31 is 1), with date1 > date2 giving a positive value and date2 > date1 a negative value
((date1.Year - date2.Year) * 12) + date1.Month - date2.Month
Or, assuming you want an approximate number of 'average months' between the two dates, the following should work for all but very huge date differences.
date1.Subtract(date2).Days / (365.25 / 12)
Note, if you were to use the latter solution then your unit tests should state the widest date range which your application is designed to work with and validate the results of the calculation accordingly.
Update (with thanks to Gary)
If using the 'average months' method, a slightly more accurate number to use for the 'average number of days per year' is 365.2425.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With