如何从Windows窗体DateTimePicker控件中只获取日期值?

时间:2009-07-16 14:53:20

标签: c# winforms date datetimepicker

我正在使用C#代码构建应用程序 如何仅从DateTimePicker控件中获取日期值?

9 个答案:

答案 0 :(得分:114)

我假设你的意思是winforms应用程序中的日期时间选择器。

在您的代码中,您可以执行以下操作:

string theDate = dateTimePicker1.Value.ToShortDateString();

或者,如果您想指定日期的格式:

string theDate = dateTimePicker1.Value.ToString("yyyy-MM-dd");

答案 1 :(得分:44)

DateTime dt = this.dateTimePicker1.Value.Date;

答案 2 :(得分:8)

将日期数据插入数据库时​​遇到此问题,您可以单独使用struct成员: 在我的情况下它是有用的,因为sql语句需要具有正确的值,你只需要添加斜杠或破折号来完成格式,不需要转换。

DateTimePicker dtp = new DateTimePicker();
String sql = "insert into table values(" + dtp.Value.Date.Year + "/" + 
dtp.Value.Date.Month + "/" + dtp.Value.Date.Day + ");";

这样你就可以在没有时间的情况下得到日期成员......

答案 3 :(得分:3)

string shortDate = dateTimePicker1.Value.ToShortDateString();

答案 4 :(得分:1)

你的意思是如何在没有时间组件的情况下获取日期?使用DateTimePicker.Value.Date 但您需要根据需要格式化输出。

答案 5 :(得分:0)

@Shoban看起来这个问题被标记为c#所以这里是适当的剪切 http://msdn.microsoft.com/en-us/library/system.windows.forms.datetimepicker.value.aspx

public MyClass()
{
    // Create a new DateTimePicker
    DateTimePicker dateTimePicker1 = new DateTimePicker();
    Controls.Add(dateTimePicker1);
    MessageBox.Show(dateTimePicker1.Value.ToString());

    dateTimePicker1.Value = DateTime.Now.AddDays(1);
    MessageBox.Show(dateTimePicker1.Value.ToString());
 } 

答案 6 :(得分:0)

之后这个问题已经给出了一个很好的答案,在WinForms中我们也可以设置一个Custom Format DateTimePicker Format属性,就像Vivek所说,这让我们要在 DateTimePicker 中的指定格式字符串中显示日期/时间,那么,它就像我们从 TextBox 中获取文本一样简单。

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

dateTimePicker1

我们现在只能通过从 DateTimePicker 获取文本来轻松获取日期:

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

enter image description here

注意:如果您计划在SQL中将仅日期数据插入日期列类型,请参阅与日期支持的字符串文字格式相关的documentation 。您不能以格式字符串 ydm 插入日期,因为不支持:

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);
   }

以上代码以下列异常结束: enter image description here

请注意。欢呼声。

答案 7 :(得分:0)

试试这个

var store = dtpDateTimePicker.Value.Date;

商店可以是任何实体对象等。

答案 8 :(得分:-1)

Datum = DateTime.Parse(DateTimePicker1.Value.ToString("dd/MM/yyyy"))