Search code examples
.nettimereal-time-updates

Constantly Update Current Time Display On A Windows Form?


I have a windows form where I want the time to constantly be updated. Right now it will take the current time from when the program was started.

For example, if I started the program at 5:30:29 PM that is what it will show the whole time the program runs.I need it to constantly be updated as the seconds tick by. So, If I started the program at 5:30:29 PM and ran it for exactly 5 minutes, the time displayed then should be 4:35:29 PM.

i want to do this in .Net


Solution

  • You need to use a Timer control and set the time interval to 1 second i.e. 1000 and for each Timer tick, update the current time. For example here is the C# solution, assume the timer timer1 and lets say you want to show the time at the label dateTimeLbl.Text then here is the timer1_tick event:

        private void timer1_Tick(object sender, EventArgs e)
        {
            dateTimeLbl.Text = DateTime.Now.ToLongTimeString();
        }