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?
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?
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" );
7 people are following this question.