Last Updated :
02 Aug, 2019
In Windows Forms, the DateTimePicker control is used to select and display date/time with a specific format in your form. In DateTimePicker control, you can set the format of the date and time that displayed in the DateTimePicker the Format Property. The values of this property are defined under DateTimePickerFormat enum and the values are:
- Custom: It is used to display the date and time in the custom format.
- Long: It is used to display the date and time in the long date format which is set by the operating system. Or in other words it display both date and time.
- Short: It is used to display the date and time in the short date format which is set by the operating system. Or in other words it display only date.
- Time: It is used to display the time which is set by the operating system.
The default value of this property is Long. You can set this property in two different ways:
1. Design-Time: It is the easiest way to set the format of the DateTimePicker as shown in the following steps:
- Step 1: Create a windows form as shown in the below image:
Visual Studio -> File -> New -> Project -> WindowsFormApp
- Step 2: Next, drag and drop the DateTimePicker control from the toolbox to the form as shown in the below images:
- Step 3: After drag and drop you will go to the properties of the DateTimePicker and set the format of the DateTimePicker as shown in the below image:
Output:
2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the format of the DateTimePicker control programmatically with the help of given syntax:
public System.Windows.Forms.DateTimePickerFormat Format { get; set; }
Here, DateTimePickerFormat enum represents the values of this property. It will throw an InvalidEnumArgumentException if the value of this property does not belong to the DateTimePickerFormat enum. The following steps show how to set the format of the DateTimePicker dynamically:
- Step 1: Create a DateTimePicker using the DateTimePicker() constructor is provided by the DateTimePicker class.
// Creating a DateTimePicker DateTimePicker dt = new DateTimePicker();
- Step 2: After creating DateTimePicker, set the Format property of the DateTimePicker provided by the DateTimePicker class.
// Setting the format dt.Format = DateTimePickerFormat.Long;
- Step 3: And last add this DateTimePicker control to the form using the following statement:
// Adding this control to the form this.Controls.Add(dt);
Example:
using
System;
using
System.Collections.Generic;
using
System.ComponentModel;
using
System.Data;
using
System.Drawing;
using
System.Linq;
using
System.Text;
using
System.Threading.Tasks;
using
System.Windows.Forms;
namespace
WindowsFormsApp48 {
public
partial
class
Form1 : Form {
public
Form1()
{
InitializeComponent();
}
private
void
Form1_Load(
object
sender, EventArgs e)
{
Label lab =
new
Label();
lab.Location =
new
Point(183, 162);
lab.Size =
new
Size(172, 20);
lab.Text =
"Select Date and Time"
;
lab.Font =
new
Font(
"Comic Sans MS"
, 12);
this
.Controls.Add(lab);
DateTimePicker dt =
new
DateTimePicker();
dt.Location =
new
Point(360, 162);
dt.Size =
new
Size(292, 26);
dt.MaxDate =
new
DateTime(2500, 12, 20);
dt.MinDate =
new
DateTime(1753, 1, 1);
dt.Format = DateTimePickerFormat.Long;
dt.Name =
"MyPicker"
;
dt.Font =
new
Font(
"Comic Sans MS"
, 12);
dt.Visible =
true
;
dt.Value = DateTime.Today;
this
.Controls.Add(dt);
}
}
}
Output:
Последнее обновление: 31.10.2015
Для работы с датами в Windows Forms имеются элементы DateTimePicker и MonthCalendar.
DateTimePicker
DateTimePicker представляет раскрывающийся по нажатию календарь, в котором можно выбрать дату. собой элемент, который с помощью перемещения ползунка позволяет вводить числовые значения.
Наиболее важные свойства DateTimePicker:
-
Format: определяет формат отображения даты в элементе управления. Может принимать следующие значения:
Custom
: формат задается разработчикомLong
: полная датаShort
: дата в сокращенном форматеTime
: формат для работы с временем -
CustomFormat: задает формат отображения даты, если для свойства
Format
установлено
значениеCustom
-
MinDate: минимальная дата, которую можно выбрать
-
MaxDate: наибольшая дата, которую можно выбрать
-
Value: определеяте текущее выбранное значение в DateTimePicker
-
Text: представляет тот текст, который отображается в элементе
При выборе даты элемент генерирует событие ValueChanged
. Например, обработаем данное собатие и присвоим выбранное значение
тексту метки:
public partial class Form1 : Form { public Form1() { InitializeComponent(); dateTimePicker1.Format = DateTimePickerFormat.Time; dateTimePicker1.ValueChanged+=dateTimePicker1_ValueChanged; } private void dateTimePicker1_ValueChanged(object sender, EventArgs e) { label1.Text = String.Format("Вы выбрали: {0}", dateTimePicker1.Value.ToLongTimeString()); } }
Свойство Value хранит объект DateTime, поэтому с ним можно работать как и с любой другой датой. В данном случае выбранная дата
преобразуется в строку времени.
В вышеприведенном случае значение dateTimePicker1.Value.ToLongTimeString()
аналогично тому тексту, который отображается в элементе.
И мы могли бы написать так:
label1.Text = String.Format("Вы выбрали: {0}", dateTimePicker1.Text);
MonthCalendar
С помощью MonthCalendar также можно выбрать дату, только в данном случае этот элемент представляет сам календарь, который не надо раскрывать:
Рассмотрим некоторые основные свойства элемента.
Свойства выделения дат:
-
AnnuallyBoldedDates: содержит набор дат, которые будут отмечены жирным в календаре для каждого года
-
BoldedDates: содержит набор дат, которые будут отмечены жирным (только для текущего года)
-
MonthlyBoldedDates: содержит набор дат, которые будут отмечены жирным для каждого месяца
Добавление выделенных дат делается с помощью определенных методов (как и удаление):
monthCalendar1.AddBoldedDate(new DateTime(2015, 05, 21)); monthCalendar1.AddBoldedDate(new DateTime(2015, 05, 22)); monthCalendar1.AddAnnuallyBoldedDate(new DateTime(2015, 05, 9)); monthCalendar1.AddMonthlyBoldedDate(new DateTime(2015, 05, 1));
Для снятия выделения можно использовать аналоги этих методов:
monthCalendar1.RemoveBoldedDate(new DateTime(2015, 05, 21)); monthCalendar1.RemoveBoldedDate(new DateTime(2015, 05, 22)); monthCalendar1.RemoveAnnuallyBoldedDate(new DateTime(2015, 05, 9)); monthCalendar1.RemoveMonthlyBoldedDate(new DateTime(2015, 05, 1));
Свойства для определения дат в календаре:
-
MinDate: определяет минимальную дату для выбора в календаре
-
MaxDate: задает наибольшую дату для выбора в календаре
-
FirstDayOfWeek: определяет день недели, с которого должна начинаться неделя в календаре
-
SelectionRange: определяет диапазон выделенных дат
-
SelectionEnd: задает конечную дату выделения
-
SelectionStart: определяет начальную дату выделения
-
ShowToday: при значении true отображает внизу календаря текущую дату
-
ShowTodayCircle: при значении true текущая дата будет обведена кружочком
-
TodayDate: определяет текущую дату. По умолчанию используется системная дата на компьютере, но с помощью данного
свойства мы можем ее изменить
Например, при установке свойств:
monthCalendar1.TodayDate= new DateTime(2015, 05, 22); monthCalendar1.ShowTodayCircle = true; monthCalendar1.ShowToday = false; monthCalendar1.SelectionStart = new DateTime(2015, 05, 1); monthCalendar1.SelectionEnd = new DateTime(2015, 05, 11);
будет следующее отображение календаря:
Наиболее интересными событиями элемента являются события DateChanged
и DateSelected
, которые возникают
при изменении выбранной в элементе даты. Однако надо учитывать, что выбранная дата будет представлять первую дату из диапазона выделенных дат:
public partial class Form1 : Form { public Form1() { InitializeComponent(); monthCalendar1.DateChanged += monthCalendar1_DateChanged; } void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e) { label1.Text = String.Format("Вы выбрали: {0}", e.Start.ToLongDateString()); // или так - аналогичный код //label1.Text = String.Format("Вы выбрали: {0}", monthCalendar1.SelectionStart.ToLongDateString()); } }
When you need to let the user select a date and/or time of day, you can use the DateTimePicker control:
You can set the control properties in the UI or programmatically:
public frmDateTime()
{
InitializeComponent();
longDatePicker.Format = DateTimePickerFormat.Long;
longDatePicker.Value = new DateTime(year: 2025, month: 1, day: 1);
}
Code language: C# (cs)
If you don’t set an initial value, it’ll default to DateTime.Now (at the time the code is executed).
The value the user picked is available via the DateTimePicker.Value property. This is a DateTime object.
private void btnSave_Click(object sender, EventArgs e)
{
DateTime longDate = longDatePicker.Value;
//save to the database etc...
}
Code language: C# (cs)
To show the DateTime as a string in the UI, you can use either the built-in format specifiers – Long (date), Short (date), Time – or use a custom format. If you use one of the built-in format specifiers, it’ll use the current system’s date/time format. I’ll show examples of using the Time format to get the time of day, using a custom format to get the date and time, and using a different control for getting non-clock time.
Time of day
Here’s an example of using the Time format to get the time of day. It displays just the time and uses the up/down picker:
Here’s how to use the Time format and make it use the up/down picker:
public frmDateTime()
{
InitializeComponent();
timeOfDayPicker.Format = DateTimePickerFormat.Time;
timeOfDayPicker.ShowUpDown = true;
}
Code language: C# (cs)
Note: DateTimePicker has two types of pickers – calendar and up/down. The up/down picker is good for when you’re only displaying the time of day.
You can set the initial time of day value with a DateTime. This is a bit awkward, because you have to set the date part of the DateTime (just use 2000-1-1):
timeOfDayPicker.Value = new DateTime(2000, 1, 1, hour: 11, minute: 0, second: 0);
Code language: C# (cs)
Here’s how to get the value:
private void btnSave_Click(object sender, EventArgs e)
{
DateTime timeOfDay = timeOfDayPicker.Value;
//save to the database etc...
}
Code language: C# (cs)
Here’s an example of using a custom format to allow the user to select both the date and time. It’s using the calendar picker:
You have to tell it you’re using a custom format and also set the custom format string:
public frmDateTime()
{
InitializeComponent();
dateTimePicker.Format = DateTimePickerFormat.Custom;
dateTimePicker.CustomFormat = "MM/dd/yyyy h:mm:ss tt";
}
Code language: C# (cs)
You can set the initial value to any DateTime object. Here’s an example of defaulting it to 2022-02-07 14:00:00:
dateTimePicker.Value = new DateTime(year: 2022, month: 2, day: 7, hour: 14, minute: 0, second: 0);
Code language: C# (cs)
Get the selected DateTime from the Value property:
private void btnSave_Click(object sender, EventArgs e)
{
DateTime dateTime = dateTimePicker.Value;
//save to the database etc...
}
Code language: C# (cs)
Non-clock time
DateTimePicker is good for time of day input – i.e. a specific time on the clock. For other types of time input – such as duration of time – you can either use a MaskedTextBox or a NumericUpDown control.
Use NumericUpDown when you only need to get one unit of time (ex: just hours). Otherwise use MaskedTextBox to handle the more complex scenario of accepting multiple units of time (ex: hours and minutes).
Here’s an example of using MaskedTextBox. Let’s say you want the user to input a countdown time in hours, minutes, and seconds:
Configure the custom format by setting the MaskedTextBox.Mask property, and set a good default value.
public frmDateTime()
{
InitializeComponent();
countdownTimerPicker.Mask = "00:00:00";
countdownTimerPicker.Text = "01:30:00";
}
Code language: C# (cs)
Note: 00:00:00 means they can only select digits (0-9) for all positions.
Get the input from MaskedTextBox.Text and parse a DateTime from this string based on your custom format. For example, this is parsing the 00:00:00 formatted string into a TimeSpan:
private void btnSave_Click(object sender, EventArgs e)
{
var timeParts = countdownTimerPicker.Text.Split(":");
int hours = Convert.ToInt32(timeParts[0]);
int minutes = Convert.ToInt32(timeParts[1]);
int seconds = Convert.ToInt32(timeParts[2]);
var timeSpan = new TimeSpan(hours, minutes, seconds);
MessageBox.Show($"Hours = {timeSpan.TotalHours}");
}
Code language: C# (cs)
This parses the “01:30:00” string into a TimeSpan and outputs the total hours as the following:
Hours = 1.5
Code language: plaintext (plaintext)
Related Articles
Provide feedback
Saved searches
Use saved searches to filter your results more quickly
Sign up