Date and Time in C#
The DateTime class gives you access to various DateTime properties including:
- Date
- Time
- Hour
- Minute
- Second
- Millisecond
- Month
- Day
- Day of the Week
- Day of the Year
To get the DateTime instance create a Windows Forms Project and add a label control
to the form. On the forms load event add the following.
this.label1.Text = DateTime.Now.ToString();
When the form loads the labels text will be the current date and time. The label
however does not reflect the updated time. To create a label that updates its text
value with the DateTime value we need to loop the update process.
We can do this with a simple Windows Forms Timer control. Add a Windows forms time
control to the form. Ensure the Timer Tick event looks similiar to the following.
private void timer1_Tick(object sender, EventArgs e)
{
this.label1.Text = DateTime.Now.ToString();
}
In the form2 load event start the timer.
private void Form2_Load(object sender, EventArgs e)
{
this.timer1.Start();
}
|