krrishna
krrishna

Reputation: 2078

Count up timer in windows phone application using c#

I have implemented count up timer (or stop watch) using the below code. I want to know if there is an efficient and standard way of implementing this in windows phone using c#.

Any suggestions would be appreciated.

private void start_click()
{
    lhours = 0; lmins = 0; lsecs = 0; lmsecs = 0;
    myDispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 1000); // 1000 Milliseconds 
    myDispatcherTimer.Tick += new EventHandler(Each_Tick);
    myDispatcherTimer.Start();
}
public void Each_Tick(object o, EventArgs sender)
{    
    lsecs = lsecs  + 1;
    if (lsecs > 59)
    {
        lsecs = 0;
        lmins = lmins + 1;
        if (lmins > 59)
        {
            lmins = 0;
            lhours = lhours + 1;
            if (lhours > 23)
            {
                lhours = 0;
                ldays = ldays + 1;
            }
        }
    }

    lblTimerDisplay.Text = ldays + ":" + lhours + ":" + lmins + ":" + lsecs + ":";
}

Upvotes: 1

Views: 4219

Answers (2)

Dan Colasanti
Dan Colasanti

Reputation: 192

Another simple way to is to save the DateTime.UtcNow when you initialize your timer, and then on the tick subtract that from the current DataTime.UtcNow.

at Timer Init:

DateTime startTime = DateTime.UtcNow;

on Tick:

TimeSpan elapsedTime = DateTime.UtcNow - startTime; 

Then you can use TimeSpan parameters to get the days, hours, minutes, and seconds for display.

Upvotes: 2

George Johnston
George Johnston

Reputation: 32258

Why not use the Stopwatch class?

System.Diagnostics.Stopwatch _sw = new System.Diagnostics.Stopwatch();
private void start_click()
{
    if (!_sw.IsRunning)
    {
        _sw.Start();
    }
    else
    {
        _sw.Stop();
        _sw.Reset();
    }
}
private void Each_Tick(object sender, EventArgs e)
{
    lblTimerDisplay.Text = _sw.Elapsed.ToString();
}

Upvotes: 5

Related Questions