c# - 将 DateTime 与来自 textbox.text 的输入一起使用

标签 c# datetime parameters

我有这段代码,执行时会给我 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/

相关文章:

c# - 在 ASP.NET MVC 中连接两个表的正确方法是什么?

r - 导入指定时区的日期时间,忽略夏令时

python - Kivy 简单倒计时分秒计时器

mysql - SQL 插入带有参数的 select 以便与事件调度程序一起使用

c++ - 如何将表达式作为参数/参数传递?

c# - System.Data.SqlClient.SqlException 与网络相关或特定于实例的错误

c# - 在 .NET 中确定复杂对象大小的方法?

c# - 我还不知道 C# 类型的对象列表

python - 如何为每 15 分钟的间隔标记 Pandas 日期时间行(在新列中)?

php - PDO 数组到字符串的转换 - 参数