title: Calculating an elapsed Time
body: <p>I want to calculate the elapsed time which a process needs to execute based on 2 strings with timestamps in the format <code>HH:mm:ss:ff</code>. Therefore I splitted those strings, turned them into an integer and subtracted them.</p>
  
  <p>What I tried is to subtract the last timestamp from the first. It also works sometimes. But I also get a lot of weird feedback out of this - for example: <code>0:0:-3:-18</code> I think this is the result of not handling the case if a value is higher than another and they get divided.</p>
  
  <p>Here is the function I use to subtract the strings: </p>
  
  <pre><code>        static string calculateElapsedTime(string startTime, string endTime)
      {
          try
          {
              string[] startTimeSplit = startZeit.Split(new char[] { ':', '.' });
              string[] endTimeSplit = endZeit.Split(new char[] { ':', '.' });
              int[] elapsedTime = new int[4];
  
              endTimeSplit[0] = Convert.ToInt32(endTimeSplit[0]) - Convert.ToInt32(startTimeSplit[0]);
              endTimeSplit[1] = Convert.ToInt32(endTimeSplit[1]) - Convert.ToInt32(startTimeSplit[1]);
              endTimeSplit[2] = Convert.ToInt32(endTimeSplit[2]) - Convert.ToInt32(startTimeSplit[2]);
              endTimeSplit[3] = Convert.ToInt32(endTimeSplit[3]) - Convert.ToInt32(startTimeSplit[3]);
  
              string elapsedTimeString = string.Format("{0}:{1}:{2}:{3}", endTimeSplit[0], endTimeSplit[1], endTimeSplit[2], endTimeSplit[3]);
  
              return elapsedTimeString;
          }
          catch( Exception ex )
          {
              Console.WriteLine(ex.Message);
              return "null";
          }
      }
  </code></pre>
  
  <p>And I got the value for the parameters by simply getting the time like:</p>
  
  <pre><code>DateTime.Now.ToString("HH:mm:ss:ff", System.Globalization.DateTimeFormatInfo.InvariantInfo);
  </code></pre>
  
  <p><strong>SOLUTION:</strong></p>
  
  <p>There is a Function called Stopwatch in the Namespace System.Diagnostics.</p>
  
  <p>You can use it as following:</p>
  
  <pre><code>Stopwatch watch = new Stopwatch();
  watch.Start();
  //Prozess
  watch.Stop();
  Console.WriteLine(watch.Elapsed);
  </code></pre>