MrMAG
MrMAG

Reputation: 1264

Searching a shorter way to display time in digital format?

Can this snippet been shorten, so that it still shows the current time
Like this: 08:24:09?
and not like this 8:24.9

My current Code:

this.lblClock = new System.Windows.Forms.Label();
this.lblClock.Text = "00:00:00";

Clock ticks:

    private void _Clock_Tick(object sender, EventArgs e)
    {
        DateTime CurrTime = DateTime.Now;

        if (CurrTime.Hour > 9 && CurrTime.Minute > 9 && CurrTime.Second > 9)
            lblClock.Text = ("" + CurrTime.Hour + ":" + CurrTime.Minute + ":" + CurrTime.Second);
        if (CurrTime.Hour < 10 && CurrTime.Minute > 9 && CurrTime.Second > 9)
            lblClock.Text = ("0" + CurrTime.Hour + ":" + CurrTime.Minute + ":" + CurrTime.Second);
        if (CurrTime.Hour > 9 && CurrTime.Minute > 9 && CurrTime.Second < 10)
            lblClock.Text = ("" + CurrTime.Hour + ":" + CurrTime.Minute + ":" + "0" + CurrTime.Second);
        if (CurrTime.Hour < 10 && CurrTime.Minute > 9 && CurrTime.Second < 10)
            lblClock.Text = ("0" + CurrTime.Hour + ":" + CurrTime.Minute + ":" + "0" + CurrTime.Second);
        if (CurrTime.Hour > 9 && CurrTime.Minute < 10 && CurrTime.Second > 9)
            lblClock.Text = ("" + CurrTime.Hour + ":" + "0" + CurrTime.Minute + ":" + CurrTime.Second);
        if (CurrTime.Hour < 10 && CurrTime.Minute < 10 && CurrTime.Second > 9)
            lblClock.Text = ("0" + CurrTime.Hour + ":" + "0" + CurrTime.Minute + ":" + CurrTime.Second);
        if (CurrTime.Hour > 9 && CurrTime.Minute < 10 && CurrTime.Second < 10)
            lblClock.Text = ("" + CurrTime.Hour + ":" + "0" + CurrTime.Minute + ":" + "0" + CurrTime.Second);
        if (CurrTime.Hour < 10 && CurrTime.Minute < 10 && CurrTime.Second < 10)
            lblClock.Text = ("0" + CurrTime.Hour + ":" + "0" + CurrTime.Minute + ":" + "0" + CurrTime.Second);
    }

Can you shorten that snippet?

Upvotes: 0

Views: 115

Answers (2)

noelicus
noelicus

Reputation: 15055

Check out the MSDN page on DateTime.ToString(...)

You can do all kind of formats!! ... including "HH:mm:ss", which is what you're after.

Upvotes: 0

Habib
Habib

Reputation: 223282

You can use DateTime Format "HH:mm:ss" to show time in label.

lblClock.Text = CurrTime.ToString("HH:mm:ss");

If you want to show AM/PM then you can do:

lblClock.Text = CurrTime.ToString("hh:mm:ss tt");

Upvotes: 3

Related Questions