Difference in months between two dates

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

    I just needed something simple to cater for e.g. employment dates where only the month/year is entered, so wanted distinct years and months worked in. This is what I use, here for usefullness only

    public static YearsMonths YearMonthDiff(DateTime startDate, DateTime endDate) {
        int monthDiff = ((endDate.Year * 12) + endDate.Month) - ((startDate.Year * 12) + startDate.Month) + 1;
        int years = (int)Math.Floor((decimal) (monthDiff / 12));
        int months = monthDiff % 12;
        return new YearsMonths {
            TotalMonths = monthDiff,
                Years = years,
                Months = months
        };
    }
    

    .NET Fiddle

提交回复
热议问题