question

HemanthB-9452 avatar image
0 Votes"
HemanthB-9452 asked Viorel-1 answered

Find Difference between Dates c#

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?

dotnet-csharp
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

Viorel-1 avatar image
0 Votes"
Viorel-1 answered

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" );


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.