2013-03-22 50 views
2

我有這段代碼,當執行時給我74天,這是正確的,但oldDate的日期必須來自TextBox。有誰知道如何做到這一點,DateTime只需要三個整數。使用DateTime從textbox.text輸入

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();   
} 
+0

正進入文本框的日期用戶?如果是這樣,你可以使用'oldDate = DateTime.Parse(myTextBox.Text)'。 – 2013-03-22 16:48:00

+0

同意..或者如果你想他們有單獨的領域,並在一起.. eack文本框可以MonthTextBox.Text = Convert.ToInt32(stringvalue) – gcoleman0828 2013-03-22 16:50:41

+0

感謝您的時間馬丁現在工作正常。 – user640707 2013-03-22 16:56:29

回答

1

可以分析來自用戶的日期:

string myDate = myTextBox.Text; 

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

// oldDate is set now 

如此說來,這取決於UI框架,更適當的控制(即:DateTimePicker從擴展WPF工具包等)可能更易於使用。

0

從您的代碼中,您必須從myTextBox中獲取oldDate,它已存儲在myDate字符串變量中。你可以將其轉換爲datetime

oldDate=Convert.ToDateTime(myDate); 

但由於它可能導致的異常使用以下

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