Reputation: 1290
I have built a countdown timer in WPF following the tutorial here: Simple COUNTDOWN With C# - WPF
Here is the code snippet I'm using:
void Timer_Tick(object sender, EventArgs e)
{
if (time > 0)
{
if (time <= 60)
{
RebootCountdownWindowTimerText.Foreground = Brushes.Red;
time--;
RebootCountdownWindowTimerText.Text
= string.Format("00:0{0}:{1}", time / 60, time % 60);
}
time--;
RebootCountdownWindowTimerText.Text
= string.Format("00:0{0}:{1}", time / 60, time % 60);
}
else
{
Timer.Stop();
serviceController.RebootComputer();
}
}
Problem is, when the timer counts down into lower seconds, the format changes. For example, counting down from 1 minute and 12 seconds:
00:01:12
00:01:11
00:01:10
00:01:9
00:01:8
etc...
How can I re-factor the code so that it properly shows a 0 in the "tens" place when counting down?
Upvotes: 2
Views: 2016
Reputation: 2716
Use the Number format D#
, where #
determines the number of digits so for example
var time =112;
Console.WriteLine(string.Format("00:{0:D2}:{1:D2}", time / 60, time % 60));
will give
00:01:52
Upvotes: 4