How to get only the date value from a Windows Form

2019-03-07 21:36发布

I'm building an application with C# code.
How do I get only the date value from a DateTimePicker control?

9条回答
一纸荒年 Trace。
2楼-- · 2019-03-07 22:07

Try this

var store = dtpDateTimePicker.Value.Date;

store can be anything entity object etc.

查看更多
你好瞎i
3楼-- · 2019-03-07 22:08

You mean how to get date without the time component? Use DateTimePicker.Value.Date But you need to format the output to your needs.

查看更多
爷、活的狠高调
4楼-- · 2019-03-07 22:09

I'm assuming you mean a datetime picker in a winforms application.

in your code, you can do the following:

string theDate = dateTimePicker1.Value.ToShortDateString();

or, if you'd like to specify the format of the date:

string theDate = dateTimePicker1.Value.ToString("yyyy-MM-dd");
查看更多
爷的心禁止访问
5楼-- · 2019-03-07 22:10

Following that this question has been already given a good answer, in WinForms we can also set a Custom Format to the DateTimePicker Format property as Vivek said, this allow us to display the date/time in the specified format string within the DateTimePicker, then, it will be simple just as we do to get text from a TextBox.

// Set the Format type and the CustomFormat string.
dateTimePicker1.Format = DateTimePickerFormat.Custom;    
dateTimePicker1.CustomFormat = "yyyy/MM/dd";

dateTimePicker1

We are now able to get Date only easily by getting the Text from the DateTimePicker:

MessageBox.Show("Selected Date: " + dateTimePicker1.Text, "DateTimePicker", MessageBoxButtons.OK, MessageBoxIcon.Information);

enter image description here

NOTE: If you are planning to insert Date only data to a date column type in SQL, see this documentation related to the supported String Literal Formats for date. You can not insert a date in the format string ydm because is not supported:

dateTimePicker1.CustomFormat = "yyyy/dd/MM";  
var qr = "INSERT INTO tbl VALUES (@dtp)";
using (var insertCommand = new SqlCommand..
{
   try
   {
     insertCommand.Parameters.AddWithValue("@dtp", dateTimePicker1.Text);
     con.Open();
     insertCommand.ExecuteScalar();
   }
   catch (Exception ex)
   {
      MessageBox.Show("Exception message: " + ex.Message, "DateTimePicker", MessageBoxButtons.OK, MessageBoxIcon.Error);
   }

the above code ends in the following Exception: enter image description here

Be aware. Cheers.

查看更多
爷、活的狠高调
6楼-- · 2019-03-07 22:16
Datum = DateTime.Parse(DateTimePicker1.Value.ToString("dd/MM/yyyy"))
查看更多
干净又极端
7楼-- · 2019-03-07 22:16
string shortDate = dateTimePicker1.Value.ToShortDateString();
查看更多
登录 后发表回答