Difference in months between two dates

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

    In my case it is required to calculate the complete month from the start date to the day prior to this day in the next month or from start to end of month.


    Ex: from 1/1/2018 to 31/1/2018 is a complete month
    Ex2: from 5/1/2018 to 4/2/2018 is a complete month

    so based on this here is my solution:

    public static DateTime GetMonthEnd(DateTime StartDate, int MonthsCount = 1)
    {
        return StartDate.AddMonths(MonthsCount).AddDays(-1);
    }
    public static Tuple CalcPeriod(DateTime StartDate, DateTime EndDate)
    {
        int MonthsCount = 0;
        Tuple Period;
        while (true)
        {
            if (GetMonthEnd(StartDate) > EndDate)
                break;
            else
            {
                MonthsCount += 1;
                StartDate = StartDate.AddMonths(1);
            }
        }
        int RemainingDays = (EndDate - StartDate).Days + 1;
        Period = new Tuple(MonthsCount, RemainingDays);
        return Period;
    }
    

    Usage:

    Tuple Period = CalcPeriod(FromDate, ToDate);
    

    Note: in my case it was required to calculate the remaining days after the complete months so if it's not your case you could ignore the days result or even you could change the method return from tuple to integer.

提交回复
热议问题