Difference in months between two dates

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

    If you want the exact number of full months, always positive (2000-01-15, 2000-02-14 returns 0), considering a full month is when you reach the same day the next month (something like the age calculation)

    public static int GetMonthsBetween(DateTime from, DateTime to)
    {
        if (from > to) return GetMonthsBetween(to, from);
    
        var monthDiff = Math.Abs((to.Year * 12 + (to.Month - 1)) - (from.Year * 12 + (from.Month - 1)));
    
        if (from.AddMonths(monthDiff) > to || to.Day < from.Day)
        {
            return monthDiff - 1;
        }
        else
        {
            return monthDiff;
        }
    }
    

    Edit reason: the old code was not correct in some cases like :

    new { From = new DateTime(1900, 8, 31), To = new DateTime(1901, 8, 30), Result = 11 },
    
    Test cases I used to test the function:
    
    var tests = new[]
    {
        new { From = new DateTime(1900, 1, 1), To = new DateTime(1900, 1, 1), Result = 0 },
        new { From = new DateTime(1900, 1, 1), To = new DateTime(1900, 1, 2), Result = 0 },
        new { From = new DateTime(1900, 1, 2), To = new DateTime(1900, 1, 1), Result = 0 },
        new { From = new DateTime(1900, 1, 1), To = new DateTime(1900, 2, 1), Result = 1 },
        new { From = new DateTime(1900, 2, 1), To = new DateTime(1900, 1, 1), Result = 1 },
        new { From = new DateTime(1900, 1, 31), To = new DateTime(1900, 2, 1), Result = 0 },
        new { From = new DateTime(1900, 8, 31), To = new DateTime(1900, 9, 30), Result = 0 },
        new { From = new DateTime(1900, 8, 31), To = new DateTime(1900, 10, 1), Result = 1 },
        new { From = new DateTime(1900, 1, 1), To = new DateTime(1901, 1, 1), Result = 12 },
        new { From = new DateTime(1900, 1, 1), To = new DateTime(1911, 1, 1), Result = 132 },
        new { From = new DateTime(1900, 8, 31), To = new DateTime(1901, 8, 30), Result = 11 },
    };
    

提交回复
热议问题