Difference in months between two dates

前端 未结 30 1140
天命终不由人
天命终不由人 2020-11-22 11:02

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

30条回答
  •  有刺的猬
    2020-11-22 11:45

    This is from my own library, will return the difference of months between two dates.

    public static int MonthDiff(DateTime d1, DateTime d2)
    {
        int retVal = 0;
    
        // Calculate the number of years represented and multiply by 12
        // Substract the month number from the total
        // Substract the difference of the second month and 12 from the total
        retVal = (d1.Year - d2.Year) * 12;
        retVal = retVal - d1.Month;
        retVal = retVal - (12 - d2.Month);
    
        return retVal;
    }
    

提交回复
热议问题