Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format text to date/time format c#

Tags:

c#

time

timer

I created a windows 8 app that will have a countdown timer. I have the code for the timer and it works fine, but instead of counting down from 120 seconds I want it to be displayed as 2:00 minutes and countdown from there. But because I use a timer I am not sure how to use the date/time property (if I can even do that). Please help me figure this out.

Here is my timer code:

 DispatcherTimer timer;
 private int counter = 120;

 public ArcadeMode()
 {
     InitializeComponent();
     timer = new DispatcherTimer();
     timer.Interval = TimeSpan.FromSeconds(1);
     timer.Tick += timer_Tick;
     timer.Start();
  }

  async void timer_Tick(object sender, object e)
  {
     await Time.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Low, () => { Time.Text = counter.ToString(); });
     counter--;
   }
like image 843
CSharpDev4Evr Avatar asked Aug 24 '26 10:08

CSharpDev4Evr


2 Answers

Time.Text = TimeSpan.FromSeconds(counter).ToString();

this will give you output like 00:01:00 if input is 60

like image 106
Damith Avatar answered Aug 27 '26 00:08

Damith


Maybe there are faster/terser ways, but this should at least display the timer the way you'd like (untested):

Time.Text = string.Format("{0}:{1}", (counter / 60), (counter % 60).ToString().PadLeft(2,'0'));
like image 23
Grant Winney Avatar answered Aug 27 '26 01:08

Grant Winney



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!