簡體   English   中英

在文本框的輸入中使用DateTime

[英]Using DateTime With input from a textbox.text

我有這段代碼,執行該代碼可以給我74天,這是正確的,但是oldDate的日期必須來自TextBox 有誰知道該怎么做,因為DateTime只需要三個整數。

private void myButton_Click(object sender, RoutedEventArgs e)
{
     string  myDate = myTextBox.Text;

     DateTime oldDate = new DateTime(2013, 6, 5);

     DateTime newDate = DateTime.Now;

     // Difference in days, hours, and minutes.
     TimeSpan ts = oldDate - newDate;
     // Difference in days.
     int differenceInDays = ts.Days;

     differenceInDays = ts.Days;

     myTextBlock.Text = differenceInDays.ToString();        
}

您可以從用戶那里解析日期:

string  myDate = myTextBox.Text;

DateTime oldDate;
if (!DateTime.TryParse(myDate, out oldDate))
{
   // User entered invalid date - handle this
}

// oldDate is set now

話雖如此,根據UI框架,更合適的控件(例如,擴展的WPF工具包中的DateTimePicker等)可能更易於使用。

從代碼中,您必須從myTextBox中獲取oldDate,並將其存儲在myDate字符串變量中。 您可以將其轉換為日期時間

oldDate=Convert.ToDateTime(myDate);

但是由於可能導致異常使用,因此

`DateTime myyDateTime;if(DateTime.TryParse(myDate, out myDateTime){//use your date difference code here}

暫無
暫無

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

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