Find Difference between Dates c#

Hemanth B 886 Reputation points
2021-10-28T16:53:52.307+00:00

Hi, I want to the find the difference between two dates in C#. I know that for total days we use:
var difference = (EndDate - StartDate).TotalDays;
But I also want find the total months & total years. How do I do that?

Developer technologies C#
{count} votes

Accepted answer
  1. Viorel 122.6K Reputation points
    2021-10-28T19:21:11.553+00:00

    Check the example that demonstrates one of approaches:

    var StartDate = new DateTime( 1985, 11, 20 );
    var EndDate = DateTime.Now;
    
    int years;
    int months;
    int days;
    
    for( var i = 1; ; ++i )
    {
        if( StartDate.AddYears( i ) > EndDate )
        {
            years = i - 1;
    
            break;
        }
    }
    
    for( var i = 1; ; ++i )
    {
        if( StartDate.AddYears( years ).AddMonths( i ) > EndDate )
        {
            months = i - 1;
    
            break;
        }
    }
    
    for( var i = 1; ; ++i )
    {
        if( StartDate.AddYears( years ).AddMonths( months ).AddDays( i ) > EndDate )
        {
            days = i - 1;
    
            break;
        }
    }
    
    Console.WriteLine( $"Difference: {years} years, {months} months, {days} days" );
    
    2 people found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.