public static string GetTotalHoursWithMinutes(DateTime datetime) { var dtSpan = DateTimeSpan.CompareDates(datetime, DateTime.Now); string totalHours = string.Empty; string totalDays = string.Empty; string totalMonths = string.Empty; int months = dtSpan.Years < 1 ? dtSpan.Months : (dtSpan.Years * 12) + dtSpan.Months; if (months > 0) { totalMonths = months == 1 ? months + " month " : months + " months "; } if (dtSpan.Days >= 0) { totalDays = dtSpan.Days <= 1 && !string.IsNullOrEmpty(totalMonths) ? dtSpan.Days + " day " : dtSpan.Days != 0 ? dtSpan.Days + " days " : string.Empty; } if (dtSpan.Hours >= 0) { totalHours = dtSpan.Hours <= 1 && !string.IsNullOrEmpty(totalDays) ? dtSpan.Hours + " hr " : dtSpan.Hours != 0 ? dtSpan.Hours + " hrs " : string.Empty; } string totalMinutes = dtSpan.Minutes <= 1 ? dtSpan.Minutes + " min" : dtSpan.Minutes + " mins"; return(totalMonths + totalDays + totalHours + totalMinutes); }
public static DateTimeSpan CompareDates(DateTime date1, DateTime date2) { if (date2 < date1) { var sub = date1; date1 = date2; date2 = sub; } DateTime current = date1; int years = 0; int months = 0; int days = 0; Phase phase = Phase.Years; DateTimeSpan span = new DateTimeSpan(); while (phase != Phase.Done) { switch (phase) { case Phase.Years: if (current.AddYears(years + 1) > date2) { phase = Phase.Months; current = current.AddYears(years); } else { years++; } break; case Phase.Months: if (current.AddMonths(months + 1) > date2) { phase = Phase.Days; current = current.AddMonths(months); } else { months++; } break; case Phase.Days: if (current.AddDays(days + 1) > date2) { current = current.AddDays(days); var timespan = date2 - current; span = new DateTimeSpan(years, months, days, timespan.Hours, timespan.Minutes, timespan.Seconds, timespan.Milliseconds); phase = Phase.Done; } else { days++; } break; } } return(span); }