views:

281

answers:

4

Hi,

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.

A: 

Find the number of seconds; subtract both numbers and then you can figure out the time difference. Depending on the programming language you use, I am positive their must be a library that can handle it.

Pran
+1  A: 

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);
berkay
A: 
//Start off with a string
string time1s = "13:45:26.836";
string time2s = "14:24:18.473";

TimeSpan interval = DateTime.Parse(time2s) - DateTime.Parse(time1s);

This will produce a result of:

  Days    0   int         Hours   0   int
  Milliseconds    637 int
  Minutes 38  int         Seconds 51  int
  Ticks   23316370000 long
  TotalDays   0.02698653935185185 double
  TotalHours  0.64767694444444446 double
  TotalMilliseconds   2331637.0   double
  TotalMinutes    38.860616666666665  double
  TotalSeconds    2331.6369999999997  double
Igor Zevaka
+2  A: 

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?

marc_s