Using DateTimePicker, a user can select Date and/or Time. We can customize the format of DateTime picker. Here are some properties of DateTime picker:
Property | Use |
CustomFormat | We can set custom format for date and time. for Eg, dd-MM-yyyy dd-MMM-yyyy MM-dd-yyyy |
Format | It determines the format of date and time to show either in standard or custom format |
MaxDate | Maximum date that can be selected |
MinDate | Minimum date that can be selected |
Value | To get selected date and time |
We can dynamically change properties of DateTime picker.
- private void Form1_Load(object sender, EventArgs e)
- {
- dateTimePicker1.CustomFormat = "dd-MM-yyyy";
- dateTimePicker1.Format = DateTimePickerFormat.Custom;
- }
Now, suppose we want to display a selected date of DateTime picker to the label in different formats. Drag one label to the form and now double click on DateTime picker control, so that it'll generate a dateTimePicker1_ValueChanged event. Now, write the following code in that event.
- private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
- {
- label1.Text = dateTimePicker1.Text + Environment.NewLine;
- label1.Text += dateTimePicker1.Value.ToString("dd-MMM-yyyy") + Environment.NewLine;
- label1.Text += dateTimePicker1.Value.ToString("dddd-MMM-yyyy") + Environment.NewLine;
- label1.Text += dateTimePicker1.Value.ToString("MM-dd-yyyy") + Environment.NewLine;
- label1.Text += dateTimePicker1.Value.ToString("dd/MM/yy") + Environment.NewLine;
- label1.Text += dateTimePicker1.Value.ToString("dddd,dd-MMM-yyyy") + Environment.NewLine;
- }
Environment.NewLine is used to add a new line to the label.
Now, whenever you select a date from DateTime picker, it'll show the result in the label.