Get Date Difference - CSharp System

CSharp examples for System:DateTime Diff

Description

Get Date Difference

Demo Code


using System;//www  .  ja va 2s.  c  om

public class Main{
        public static DateTime GetDateDifference(DateTime startDate, DateTime endDate, ref int years, ref int months)
        {

            TimeSpan Span = endDate - startDate;
            DateTime diffDate = DateTime.MinValue + Span;

            //The month can be one out as different months have different days in them. 
            int daysInStartDateMonth = DateTime.DaysInMonth(startDate.Year, startDate.Month);
            int daysInEndDateMonth = DateTime.DaysInMonth(endDate.Year, endDate.Month);
            int diff = daysInEndDateMonth - daysInStartDateMonth;
            diffDate = diffDate.AddDays(diff);//So adjust the diffDate manually

            years = diffDate.Year - 1;
            months = diffDate.Month - 1;
            return diffDate;
        }
}

Related Tutorials