Skip to content
Sign upLog in
← Back to Community

How to make a stopwatch in c#

Profile icon
Bunnytoes

Today you will learn to make a stopwatch in pure c#, nothing else

Start by adding

using System.Diagnostics;

that is all the using statements you need, next create a Stopwatch by doing this

Stopwatch stopWatch = new Stopwatch();

name it anything you want
then prompt the user to press a key and then clear it by doing this

Console.ReadKey(); Console.Clear();

then do this

stopWath.Start(); //use whatever you named your stopwatch

then when the user presses another key

Console.ReadKey(); Console.Clear(); stopWatch.Stop(); //whatever your stopwatch is called

then this is the hard part, create a TimeSpan

TimeSpan ts = stopWatch.Elapsed;

then do this code

string elapsedTime = String.Format("{0:00}:{1:00}.{2:00}", ts.Minutes, ts.Seconds, ts.Milliseconds / 10); Console.WriteLine($"{elapsedTime} seconds has passed");

if you want hours as well do this

string elapsedTime = String.Format("{1:00}:{2:00}.{3:00}:{4:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); Console.WriteLine($"{elapsedTime} seconds has passed");

the string.format is how the elapsed time will be displayed when you actually run it
I hope this was helped and you enjoyed, so now bye

Voters
Profile icon
Yusuf-KhuzaimaK
Profile icon
MahaRKA
Profile icon
AlejandroAzua
Profile icon
Bunnytoes