Search code examples
c#visual-studio-2010uptime

getting program uptime


I'm beginner to programming. This is my code:

private void timer1_Tick(object sender, EventArgs e)
{
    sec++;
    textBoxSeconds.Text = sec.ToString();
    if (sec > 59)
    {
        sec = 0;
        textBoxSeconds.Text = sec.ToString();
        min++;
        textBoxMinutes.Text = min.ToString();
    }
}

time goes too fast;/ and it stops for few sec sometimes. Hope someone can help me:) *EDIT//* thanks for help:) it works, but i still have a problem i didnt menton earlier. time stops sometimes for 1-2 sec, idk why. maybe because of some loops?


Solution

  • This is the wrong approach. When you program starts just save a DateTime instance, i.e. startTime. In your timer tick handler calculate the difference between the current time and the start time and display that.

    private DateTime startTime = DateTime.Now;
    
    private void timer1_Tick(object sender, EventArgs e)
    {
        var delta = DateTime.Now - startTime;
        textBoxSeconds.Text = delta.Seconds.ToString("n0");
        textBoxMinutes.Text = Math.Floor(delta.TotalMinutes).ToString("n0");
    }