[英]Using DateTime With input from a textbox.text
I have this code that when executed gives me 74 Days, which is correct, but the date for oldDate
has to come from a TextBox
. 我有这段代码,执行该代码可以给我74天,这是正确的,但是
oldDate
的日期必须来自TextBox
。 Does anyone know how to do this as the DateTime
only takes three integers. 有谁知道该怎么做,因为
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();
}
You can parse the date from the user: 您可以从用户那里解析日期:
string myDate = myTextBox.Text;
DateTime oldDate;
if (!DateTime.TryParse(myDate, out oldDate))
{
// User entered invalid date - handle this
}
// oldDate is set now
That being said, depending on the UI framework, a more appropriate control (ie: the DateTimePicker
from the extended WPF toolkit, etc) may be easier to use. 话虽如此,根据UI框架,更合适的控件(例如,扩展的WPF工具包中的
DateTimePicker
等)可能更易于使用。
From your code you have to obtain oldDate from myTextBox, which you have stored in myDate string variable. 从代码中,您必须从myTextBox中获取oldDate,并将其存储在myDate字符串变量中。 You can convert it to datetime
您可以将其转换为日期时间
oldDate=Convert.ToDateTime(myDate);
But since it might cause exception use following 但是由于可能导致异常使用,因此
`DateTime myyDateTime;if(DateTime.TryParse(myDate, out myDateTime){//use your date difference code here}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.