How to get the time difference between two DateTimes using C#

Here’s a quick an easy way to show the time difference between two DateTime objects using C#.

The DateTime structure has an overridden subtract operator which return a TimeSpan object when subtracting two DateTimes:

public static TimeSpan operator -(DateTime d1, DateTime d2);

You can then use this TimeSpan to get the amount of time between each DateTime:


DateTime fromDate = DateTime.Now.AddDays(-1).AddMinutes(-10).AddSeconds(-20);
DateTime toDate = DateTime.Now;
TimeSpan timeSpan = toDate - fromDate;

string timeString =
    string.Format(
        "{0:00}:{1:00}:{2:00}",
        (timeSpan.Days * 24) + timeSpan.Hours,
        timeSpan.Minutes,
        timeSpan.Seconds
    );

In the above example I’m comparing a date in the past to the current date. This could be useful for working out the total amount of time that has passed since something has happened.

I’m then using the Hours, Minutes and Seconds properties of the TimeSpan to format a string displaying the amount of time. If the hours goes over 24 then the Days property is used, so for my hours I’m also adding on the number of days multiplied by 24.

Posted on by Joe in C#

3 Responses to How to get the time difference between two DateTimes using C#

  1. eric

    You can do like this also

    System.TimeSpan diff = secondDate.Subtract(firstDate);

    http://csharp.net-informations.com/statements/csharp-date-difference.htm

    eric

  2. Pingback: [RESOLVED]How to get SUM of Time in c#.net | ASP Questions & Answers

  3. Pingback: [RESOLVED]How to get SUM of Time in c#.net | ASP Web Form Data Control

Add a Comment