Difference in months between two dates

前端 未结 30 1629
天命终不由人
天命终不由人 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:41

    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.

    public int GetMonths(DateTime startDate, DateTime endDate)
    {
        if (startDate > endDate)
        {
            throw new Exception("Start Date is greater than the End Date");
        }
    
        int months = ((endDate.Year * 12) + endDate.Month) - ((startDate.Year * 12) + startDate.Month);
    
        if (endDate.Day >= startDate.Day)
        {
            months++;
        }
    
        return months;
    }
    

提交回复
热议问题