Difference in months between two dates

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

    Here is a simple solution that works at least for me. It's probably not the fastest though because it uses the cool DateTime's AddMonth feature in a loop:

    public static int GetMonthsDiff(DateTime start, DateTime end)
    {
        if (start > end)
            return GetMonthsDiff(end, start);
    
        int months = 0;
        do
        {
            start = start.AddMonths(1);
            if (start > end)
                return months;
    
            months++;
        }
        while (true);
    }
    

提交回复
热议问题