我有这段代码,执行时会给我 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
等)可能更易于使用。
关于c# - 将 DateTime 与来自 textbox.text 的输入一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15575684/