Search code examples
c#stopwatch

How to check TimeSpan/Stopwatch.Elapsed includes second/minutes/hours


I have a stopwatch which just simply counts upwards for a certain period of time and as of the moment, it shows its current status as such:

HH:MM:SS:MLS
00:00:50.876

..but I only want it to shows the zeros under HH & MM if the stopwatch even reaches that amount of time. So the HH & MM are hidden until the stopwatch gets past 60 seconds for minutes or 60 minutes for hours.

I'm planning on using an if statement inside a while loop so it would check this every time, but have no idea how I would check if the TimeSpan/Stopwatch has even reached an hour/minute.

My code for the stopwatch:

static Stopwatch ElapsedTimeStopwatch = new Stopwatch();

ElapsedTimeStopwatch.Start();
while (ElapsedTimeStopwatch.IsRunning)
{
    TimeSpan etts = ElapsedTimeStopwatch.Elapsed;

    string ElapsedTime = etts.ToString(@"hh\:mm\:ss\:fff");

    UpdateElapsedTimeTextBlock(ElapsedTime, ElapsedTimeTextBlock);
}

[...]

ElapsedTimeStopwatch.Stop();
ElapsedTimeStopwatch.Reset();

Solution

  • You could of course check the Total... properties, and base your format on that:

    string format;
    
    if (etts.TotalHours >= 1)
    {
        format = @"hh\:mm\:ss\:fff";
    }
    else if (etts.TotalMinutes >= 1)
    {
        format = @"mm\:ss\:fff";
    }
    else
    {
        format = @"ss\:fff";
    }
    
    string ElapsedTime = etts.ToString(format);