Posts Tagged dates

Calculating the duration between two DateTime’s, i.e. X days, Y hours, Z minutes, Q seconds, W miliseconds

Posted by Ozer Senturk on Tuesday, 9 March, 2010
/// <summary>
/// Generates a string representation of duration between startTime and endTime
/// </summary>
/// <param name="startTime">The start of time</param>
/// <param name="endTime">The end of time</param>
/// <returns>The representation of the duration, i.e. 2 days 3 hours 4 minutes 4 seconds 279 milliseconds</returns>
public static string Duration(DateTime startTime, DateTime endTime)
{
    if (endTime == DateTime.MinValue)
        return "";

    TimeSpan timeSpan = endTime - startTime;

    StringBuilder sb = new StringBuilder();
    if (timeSpan.Days > 0)
        sb.Append(String.Format("{0} days ", timeSpan.Days));
    if (timeSpan.Hours > 0)
        sb.Append(String.Format("{0} hours ", timeSpan.Hours));
    if (timeSpan.Minutes > 0)
        sb.Append(String.Format("{0} minutes ", timeSpan.Minutes));
    if (timeSpan.Seconds > 0)
        sb.Append(String.Format("{0} seconds ", timeSpan.Seconds));
    if (timeSpan.Milliseconds > 0)
        sb.Append(String.Format("{0} milliseconds ", timeSpan.Milliseconds));

    return sb.ToString().Trim();
}