如何将系统日期格式(如3/18/2014)转换为DateTime中可读的格式?我想从两次约会中得到总天数,这两次约会将来自两个TextBoxes。
我尝试过这样的语法:
DateTime tempDateBorrowed = DateTime.Parse(txtDateBorrowed.Text);
DateTime tempReturnDate = DateTime.Parse(txtReturnDate.Text);
TimeSpan span = DateTime.Today - tempDateBorrowed;
rf.txtDaysBorrowed.Text = span.ToString();
但是tempDateBorrowed
总是返回DateTime
变量的最小日期。我认为这是因为DateTime没有正确地解析我的系统日期格式。因此,它不正确地显示天数。例如,如果我尝试分别进入3/17/2014和3/18/2014,我总是有-365241天而不是1天。
编辑:我希望我的区域设置是非特定的,所以我没有为我的日期格式设置特定的区域设置。(顺便说一句,我的系统格式是en-US)
发布于 2014-03-18 01:21:20
改用DateTime.ParseExact
方法。
参见下面的示例代码(自从使用控制台应用程序编写这段代码以来,我一直使用字符串而不是TextBoxes )。希望这能有所帮助。
class Program
{
static void Main(string[] args)
{
string txtDateBorrowed = "3/17/2014";
string txtReturnDate = "3/18/2014";
string txtDaysBorrowed = string.Empty;
DateTime tempDateBorrowed = DateTime.ParseExact(txtDateBorrowed, "M/d/yyyy", null);
DateTime tempReturnDate = DateTime.ParseExact(txtReturnDate, "M/d/yyyy", null);
TimeSpan span = DateTime.Today - tempDateBorrowed;
txtDaysBorrowed = span.ToString();
}
}
发布于 2014-03-18 01:07:24
ToString不是日子
TimeSpan.TotalDays性质
发布于 2014-03-18 01:10:39
您可以尝试在文本框中指定日期时间的格式,如下所示
DateTime tempDateBorrowed = DateTime.ParseExact(txtDateBorrowed.Text.Trim(), "M/d/yyyy", CultureInfo.InvariantCulture);
DateTime tempReturnDate = DateTime.ParseExact(txtReturnDate.Text.Trim(), "M/d/yyyy", CultureInfo.InvariantCulture);
此外,您可能必须检查文本框中的值是否有效。
https://stackoverflow.com/questions/22468432
复制相似问题