views:

19

answers:

1

I have a stopwatch timer that I've added to my program. It's working fine on my Win 7 machine, and on the Vista machines I've tried, but in XP, the hrs and mins zeros disappear when the timer starts, but will come back if I reset the timer. Here's all of my code that I have for the timer. I've removed everything that didn't seem necessary to diagnose the problem:

  DateTime startTime, stopTime;
    TimeSpan stoppedTime;
    bool reset;



    private void btnStopwatchStart_Click(object sender, EventArgs e)
    {
        // Start timer and get starting time
        if (reset)
        {
            reset = false;
            startTime = DateTime.Now;
            stoppedTime = new TimeSpan(0);
        }
        else
        {
            stoppedTime += DateTime.Now - stopTime;
        }
        stopwatchTimer.Enabled = true;
    }

    private void btnStopwatchReset_Click(object sender, EventArgs e)
    {
        // Reset displays to zero
        reset = true;
        lblElapsed.Text = "00:00:00";
    }

    private void btnStopwatchPause_Click(object sender, EventArgs e)
    {
        // Stop timer
        stopTime = DateTime.Now;
        stopwatchTimer.Enabled = false;
    }

    private void stopwatchTimer_Tick(object sender, EventArgs e)
    {
        DateTime currentTime;
        // Determine elapsed and total times
        currentTime = DateTime.Now;

        // Display times
        lblElapsed.Text = HMS(currentTime - startTime - stoppedTime);
    }

    private string HMS(TimeSpan tms)
    {
        // Format time as string, leaving off last six decimal places
        string s = tms.ToString();
        return (s.Substring(0, s.Length - 6));
    }
+1  A: 

Older version of .NET, maybe? Your HMS() function critically depends on the number of digits generated by TimeSpan.ToString(). Here's a better way to format it:

    private static string HMS(TimeSpan tms) {
        return new DateTime(tms.Ticks).ToString("H:mm:ss");
    }
Hans Passant
Thanks! It's working just fine here on the Win7 machine (with .NET 4.0). It's going to be tested on an XP machine here in a few hours.
EvanRyan
Yes, TimeSpan.ToString() was modified in .NET 4.0. The replacement I gave you will work consistently on any version of .NET
Hans Passant