-2

Is there any suggestion on how to optimize, and shorten this if case:

if (secound < 10)
    TimerLabel.Text = $"{Hour}:{Minute}:0{secound}";
if (Minute< 10)
    TimerLabel.Text = $"{Hour}:0{Minute}:{secound}";
if (Hour < 10)
    TimerLabel.Text = $"0{Hour}:{Minute}:{secound}";
if(secound <10 && Minute < 10)
    TimerLabel.Text = $"{Hour}:0{Minute}:0{secound}";
if (secound < 10 && Hour < 10)
    TimerLabel.Text = $"0{Hour}:{Minute}:0{secound}";
if(Minute < 10 && Hour < 10)
    TimerLabel.Text = $"0{Hour}:0{Minute}:{secound}";
if(Hour < 10 && Minute < 10 && secound < 10)
    TimerLabel.Text = $"0{Hour}:0{Minute}:0{secound}";
3

4 Answers 4

8

It is just one line. Use string numeric formatting

TimerLabel.Text = $"{Hour:D2}:{Minute:D2}:{secound:D2}";

The letter D (format specifier) followed by a numeric values (precision specifier) instruct the formatting code to supply enough "0" characters to fill the required space

0
5

Just use String.Format syntax

TimerLabel.Text = $"{Hour:00}:{Minute:00}:{Second:00}");
0

It should be enough to specify the numeric format of each component:

 TimerLabel.Text = $"{Hour:D2}:{Minute:D2}:{secound:D2}";

D2 = decimal output, two characters

0

Often we don't want to work with Hour, Minute, second separately (just imagine how comlex it'll be to perform a very simple operation like adding 5 hours, 59 minutes and 47 seconds), but with TimeSpan which has been specially desinged for this:

   TimeSpan period = new TimeSpan(Hour, Minute, second);

   ...

   TimerLabel.Text = period.ToString();

In case Hour, Minute, second means time, not a period use DateTime:

   DateTime time = DateTime.Today.Add(new TimeSpan(Hour, Minute, second));

   ...

   TimerLabel.Text = time.ToString("HH:mm:ss");
1
  • Im making a form (Timer form) to display a timer but timespan does not do the Job for my case (and i didnt know about the timespan interface so thanks !).
    – The Sphynx
    Aug 27, 2018 at 13:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.