Search code examples
c#wpftimespandispatchertimer

Include hour in timer countdown


I am trying to create a countdown that includes hours.

private int time = 3660;        

public MainWindow()
{
    var vm = new TimerViewModel();

    InitializeComponent();

    // get display setting - 2 means extended
    int displayType = Screen.AllScreens.Length;

    // set the windows datacontext
    DataContext = vm;

    // set up the timedispatcher
    dt.Interval = new TimeSpan(0, 0, 1);
    dt.Tick += Timer_Tick;
}   

private void Timer_Tick(object sender, EventArgs e)
{
    switch(time)
    {
        case int x when x > 10 && x <= 20:                 
            TimerPreview.Foreground = Brushes.Orange;

            time--;
            break;

        .....................

        default:
            TimerPreview.Foreground = Brushes.LimeGreen;
            time--;
            break;
    }

    TimerPreview.Content = string.Format("00:{0:00}:{1:00}",  time / 60, time % 60);
}

I cannot work out how to get the countdown working correctly with hours. It works great with minutes and seconds.

TimerPreview.Content = string.Format("{0:00}:{1:00}:{2:00}", time ???, time ??? 60, time % 60);

I have tried a number of combinations but have failed to find a solution. What am I missing? Many thanks.


Solution

  • Use 3600 (the number of seconds in an hour), and use the modulus operator on the minutes just like you're doing on the seconds (since you want 60 minutes to appear to roll over into a new hour):

    TimerPreview.Content =
        string.Format("{0:00}:{1:00}:{2:00}", time / 3600, (time / 60) % 60, time % 60);
    
    //  320 -> 00:05:20
    // 7199 -> 01:59:59
    // 7201 -> 02:00:01