ZeroByter
ZeroByter

Reputation: 374

C# get current system time

So I have a program that I need to be able to get the current time. This is a winform and I have a timer that starts up when the winform is loaded and the interval is 1000. Every tick it checks the time and sets a label on the winform to display that time. I use DateTime.Now.Hour; to determine the hour (which is just what I need). My problem is even though this code is on a timer it only displays the time that was when the winform started and doesnt update it. What do I do to get the current and updating hour of the day?

EDIT:

Here is the code

//code for hour variable
private int time = DateTime.Now.Hour;

//Code for timer
private void mainTimer_Tick(object sender, EventArgs e)
        {
            //code run every time mainTimer gets a tick
            label1.Text = time.ToString();
        }

Upvotes: 2

Views: 16238

Answers (2)

Creator
Creator

Reputation: 1512

    private void Clock(object sender, EventArgs e)
    {
        DateTime dtn = DateTime.Now.Hour;
        label1.Text = dtn.ToString();
    }

then put timer tick on it

Upvotes: 1

Rohit Vats
Rohit Vats

Reputation: 81233

Your class field won't be re-evaluated again until you set it explicitly.

This is how you should do it:

label1.Text = DateTime.Now.Hour.ToString();

Upvotes: 9

Related Questions