[英]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.