public static string ReadableDiff(this DateTime startTime, DateTime endTime)
{
string result;
int seconds = endTime.Second - startTime.Second;
int minutes = endTime.Minute - startTime.Minute;
int hours = endTime.Hour - startTime.Hour;
int days = endTime.Day - startTime.Day;
int months = endTime.Month - startTime.Month;
int years = endTime.Year - startTime.Year;
if (seconds < 0)
{
minutes--;
seconds += 60;
}
if (minutes < 0)
{
hours--;
minutes += 60;
}
if (hours < 0)
{
days--;
hours += 24;
}
if (days < 0)
{
months--;
int previousMonth = (endTime.Month == 1) ? 12 : endTime.Month - 1;
int year = (previousMonth == 12) ? endTime.Year - 1 : endTime.Year;
days += DateTime.DaysInMonth(year, previousMonth);
}
if (months < 0)
{
years--;
months += 12;
}
//put this in a readable format
if (years > 0)
{
result = years.Pluralize(YEAR);
if (months != 0)
result += ", " + months.Pluralize(MONTH);
result += " ago";
}
else if (months > 0)
{
result = months.Pluralize(MONTH);
if (days != 0)
result += ", " + days.Pluralize(DAY);
result += " ago";
}
else if (days > 0)
{
result = days.Pluralize(DAY);
if (hours != 0)
result += ", " + hours.Pluralize(HOUR);
result += " ago";
}
else if (hours > 0)
{
result = hours.Pluralize(HOUR);
if (minutes != 0)
result += ", " + minutes.Pluralize(MINUTE);
result += " ago";
}
else if (minutes > 0)
result = minutes.Pluralize(MINUTE) + " ago";
else
result = seconds.Pluralize(SECOND) + " ago";
return result;
}