Jump to content

Check out our Community Blogs

Register and join over 40,000 other developers!

Recent Status Updates

View All Updates

- - - - -

C# and WPF countdown timer

timer countdown countdown timer

  • Please log in to reply
1 reply to this topic

#1 Jrb


    CC Regular

  • Member
  • PipPipPip
  • 48 posts

Posted 10 October 2011 - 08:11 PM

Hi all.

I'm trying to make a C#/WPF app with a date countdown. The problem I'm having is I'm trying to use the t.days, t.minutes, t.seconds variables in textblocks and then use a timer to count them down. I just have no idea on how to implement this.

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace WpfApplication2

	public partial class MainWindow : Window
		private int _time;
    	        private DispatcherTimer _countdownTimer;
		public MainWindow()
			DateTime eventTime = DateTime.Parse("1/20/2012 12:00:01 AM");
                        DateTime startDate = DateTime.Now;
                        TimeSpan t = eventTime - startDate;
                        string countDown = string.Format("{0} Days, {1} Hours, {2} Minutes, {3} Seconds til launch.", t.Days, t.Hours, t.Minutes, t.Seconds);
		         _countdownTimer = new DispatcherTimer();
        	         _countdownTimer.Interval = new TimeSpan(0,0,1);
        	         _countdownTimer.Tick += new EventHandler(CountdownTimerStep);

Basically what I'm trying to do: I have three textblocks. One for days, one for minutes, and one for seconds. I want to use the timer to countdown the days, minutes, and seconds in a live format. Obviously when the seconds reach zero it'll have to subtract 1 from the minute textblock and reset the seconds textblock. Same for the others.

Anyone have any ideas or previously used code?
  • 0

#2 gregwarner


    Obi Wan of Programming

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1586 posts
  • Location:Arkansas
  • Programming Language:C, Java, C++, C#, PHP, Transact-SQL

Posted 11 October 2011 - 11:47 AM

Could be done with some simple if statements. After subtracting one from the seconds value, you check:

if seconds < 0:
  add 60 to seconds
  subtract 1 from minutes

You would then do the same thing for the minutes, and finally for the hours, each time adding an appropriate amount to the value and subtracting one from the next.
  • 0

Hofstadter's Law: It always takes longer than you expect, even when you take into account Hofstadter's Law.
– Douglas Hofstadter, Gödel, Escher, Bach: An Eternal Golden Braid

Also tagged with one or more of these keywords: timer, countdown, countdown timer

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download