簡體   English   中英

如何僅從Windows窗體DateTimePicker控件中獲取日期值?

[英]How to get only the date value from a Windows Forms DateTimePicker control?

我正在使用C#代碼構建應用程序。
如何僅從DateTimePicker控件獲取日期值?

我假設您是指Winforms應用程序中的日期時間選擇器。

在您的代碼中,您可以執行以下操作:

string theDate = dateTimePicker1.Value.ToShortDateString();

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

string theDate = dateTimePicker1.Value.ToString("yyyy-MM-dd");
DateTime dt = this.dateTimePicker1.Value.Date;

在將日期數據插入數據庫時​​,我遇到了這個問題,您可以單獨使用struct成員:就我而言,這很有用,因為sql語句需要具有正確的值,而您只需要添加斜杠或破折號即可完成格式,無需轉換。

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

這樣一來,您只需要時間即可獲得約會成員...

string shortDate = dateTimePicker1.Value.ToShortDateString();

您的意思是如何在沒有時間成分的情況下獲取日期? 使用DateTimePicker.Value.Date但是您需要根據需要格式化輸出。

@Shoban看來問題被標記為c#,所以這里是適當的摘錄http://msdn.microsoft.com/zh-cn/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());
 } 

在此問題已經得到很好的回答之后,在WinForms中,我們還可以像Vivek所說的那樣將Custom Format設置為DateTimePicker Format屬性,這使我們可以在DateTimePicker中以指定的格式字符串顯示日期/時間,就像我們從TextBox獲取文本一樣,這將很簡單。

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

dateTimePicker1

現在,我們只能通過從DateTimePicker獲取文本來輕松獲取Date:

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

在此處輸入圖片說明

注意:如果您打算在SQL中將“僅日期”數據插入到日期列類型中,請參閱此文檔 ,該文檔date的受支持的字符串文字格式有關。 您不能以格式字符串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);
   }

上面的代碼以以下異常結尾: 在此處輸入圖片說明

意識到。 干杯。

嘗試這個

var store = dtpDateTimePicker.Value.Date;

store可以是任何實體對象等。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM