C# elapsed time on a timer?

To just get ellapsed time, the StopWatch class will probably be easier to use.

Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();

// do stuff

stopWatch.Stop();
long duration = stopWatch.ElapsedMilliseconds;

Here is an example that uses the stopwatch from System.Diagnostics namespace:

var stopWatch = new Stopwatch();
stopWatch.Start();

Thread.Sleep(10000);
stopWatch.Stop();

// Get the elapsed time as a TimeSpan value.
var ts = stopWatch.Elapsed;

// Format and display the TimeSpan value.
string elapsedTime = $"{ts.Hours}:{ts.Minutes}:{ts.seconds}.{ts.Milliseconds / 10}",
    
Console.WriteLine("RunTime " + elapsedTime);

Tags:

C#