Problem finding difference between two time intervals

10,437

Solution 1

Basically, what you need to do is put those time values into DateTime structures. Once you have your two DateTime variables, just subtract them from one another - the result is a variable of type TimeSpan:

DateTime dt1 = new DateTime(2010, 5, 7, 13, 45, 26, 836);
DateTime dt2 = new DateTime(2010, 5, 7, 14, 24, 18, 473);

TimeSpan result = dt2 - dt1;
string result2 = result.ToString();

TimeSpan has a ton of properties that get sets - the difference in all sorts of units, e.g. milliseconds, seconds, minutes etc. You can also just do a .ToString() on it to get a string representation of the result. In result2, you'll get something like this:

00:38:51.6370000

Is that what you're looking for?

Solution 2

i'm posting an example;

you can check it and adapt your program,

/* Read the initial time. */
    DateTime startTime = DateTime.Now;
    Console.WriteLine(startTime);

    /* Do something that takes up some time. For example sleep for 1.7 seconds. */
    Thread.Sleep(1700);

    /* Read the end time. */
    DateTime stopTime = DateTime.Now;
    Console.WriteLine(stopTime);

    /* Compute the duration between the initial and the end time. 
     * Print out the number of elapsed hours, minutes, seconds and milliseconds. */
    TimeSpan duration = stopTime - startTime;
    Console.WriteLine("hours:" + duration.Hours);
    Console.WriteLine("minutes:" + duration.Minutes);
    Console.WriteLine("seconds:" + duration.Seconds);
    Console.WriteLine("milliseconds:" + duration.Milliseconds);
Share:
10,437
SyncMaster
Author by

SyncMaster

Updated on October 26, 2022

Comments

  • SyncMaster
    SyncMaster over 1 year

    How can I find difference between two time intervals. Like 13:45:26.836 - 14:24:18.473 which is of the format "Hour:Min:Sec:Millisecs". Now i need to find the time difference between these two times.

    How can i do this in C#.?

    Thanks in advance.