How to: Display the Date and Time in Your Application

You can display the date on a Windows Form by using calendar controls, such as the MonthCalendar control or a DateTimePicker control. The DateTimePicker control also enables you to display the time.

You can also use these controls to collect input from the user to use the date or time selected elsewhere in your application. The MonthCalendar control enables you to select a range of dates. For more information, see How to: Select a Range of Dates in a Calendar Control.

To display a date by using a MonthCalendar control

  1. On the File menu, click New Project.

    The New Project dialog box appears.

  2. Click Windows Forms Application and then click OK.

  3. Add a Label control to the form, with the default name Label1.

  4. Add a MonthCalendar control to the form, with the default name MonthCalendar1.

  5. Double-click the form to add the default Load event handler in the Code Editor and add the following code. This code assigns the selected date (today's date) to the Text property of the label in short date format.

    this.label1.Text =
  6. Create a DateChanged event handler for the MonthCalendar1 control. You can do this by double-clicking the control in the designer.

  7. Add the following code to the MonthCalendar_DateChanged event handler. This code sets the label to the selected date, but this time in long date format.

    this.label1.Text =
  8. Press F5 to run the program.

  9. When the form opens, change the date by clicking a date in the MonthCalendar control.

  10. Verify that the date is updated in the label.

To display the time by using a DateTimePicker control

  1. Add a DateTimePicker control to the form, with the default name DateTimePicker1.

  2. Double-click the form to switch to the Code Editor.

  3. Add the following code to the Form1_Load event handler. This code sets the format of the control to display a time, instead of a date, and lets the user change the time that is displayed.

    this.dateTimePicker1.Format = DateTimePickerFormat.Time;
    this.dateTimePicker1.Width = 100;
    this.dateTimePicker1.ShowUpDown = true;
  4. Add a Button control to the form, and change the following properties.






    Current Time

  5. Double-click the button to add the default Click event handler.

  6. Add the following code to set the time back to the current time.

    this.dateTimePicker1.Value = DateTime.Now;
  7. Press F5 to run the program.

  8. When the form opens, change the time by selecting the hour, minute, or seconds and click the up or down arrow.

  9. Click Current Time to reset the control to the current time.

See Also


Designing a User Interface in Visual C#

Other Resources

Date and Time Controls

Visual C# Guided Tour