C# get current system time

12,747

Solution 1

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();

Solution 2

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

then put timer tick on it

Share:
12,747
ZeroByter
Author by

ZeroByter

//Life motto if(You.sad() == TRUE) { sad().stop(); beAwesome(); }

Updated on June 15, 2022

Comments

  • ZeroByter
    ZeroByter almost 2 years

    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();
            }