【问题标题】:String not recogized as valid DateTime - from web page字符串未被识别为有效的日期时间 - 来自网页
【发布时间】:2015-05-24 06:15:40
【问题描述】:

尝试向 .NET 网页添加日期验证(使用 C#)。比较开始日期和结束日期以确保结束日期 > 开始日期。

由于某种原因,我收到以下错误:

字符串未被识别为有效的日期时间。

现在我承认这是我第一次使用 DateTime 方法,所以我可能还没有完全理解它,但据我所知,我的代码应该不错。

谁能告诉我我错过了什么?

String startD = Request["txtStartDate"]; //requesting string from textbox "txtStartDate"
String endD = Request["txtEndDate"];
DateTime start = DateTime.Parse(startD); //line that throws the error
DateTime end = DateTime.Parse(endD);

【问题讨论】:

  • 我们可以看到 Request["txtStartDate"] 正在返回吗?
  • 请向我们展示Request["txtStartDate"]Request["txtEndDate"]的内容。您可以通过调试或控制台输出或任何其他方式获取它们。
  • @TolgaEvcimen 是的,我同意。除非我们看到输入,否则我们什么都做不了
  • 用户在 txtStartDate 中输入的值不是 DateTime 数据类型的有效输入。请参阅标准日期和时间格式字符串here
  • 假设我正确理解了您的问题,txtStartDate / txtEndDate 请求仅返回格式为 MM/dd/yyyy 的文本字符串。

标签: c# datetime


【解决方案1】:

出现错误是因为您提供的输入位于MM/dd/yyyy 中。 .net 可以将格式视为dd/MM/yyy。因此,如果您的输入是02/13/2015,它可能会失败,因为没有超过 12 的月份。所以试试ParseExact

下面试试

String startD = Request["txtStartDate"]; 
String endD = Request["txtEndDate"];
DateTime start = DateTime.ParseExact(startD, "MM/dd/yyyy",
                  new CultureInfo("en-US"),DateTimeStyles.None);
DateTime end = DateTime.ParseExact(endD, "MM/dd/yyyy",
                  new CultureInfo("en-US"),DateTimeStyles.None);

 String startD = Request["txtStartDate"]; 
 String endD = Request["txtEndDate"];
 DateTime start = DateTime.ParseExact(startD,"MM/dd/yyyy",
                        System.Globalization.CultureInfo.InvariantCulture);
    DateTime end = DateTime.ParseExact(endD,"MM/dd/yyyy",
                        System.Globalization.CultureInfo.InvariantCulture);

欲了解更多信息Msdn Doc for ParseExact

【讨论】:

  • 感谢 Sachu,但它仍然会引发相同的错误。我想我看错了。我认为sohaiby在他上面的评论中是正确的,我的文本框输入的格式就是问题所在。我得回去再研究一下。谢谢你们的帮助。
  • @tworley1977 当您调试时分配给 startD 和 endD 的值是什么?如果是 MM/dd/yyyy,上面的代码肯定会在 C# 中工作
  • 只是想联系基地,让你们知道我发现了问题。这根本不是我的 DateTime 代码。我原来的 DateTime 代码和 Sachu 提供的代码都可以正常工作。问题最终是我没有将文本框中的值放入变量中。这是我一直忽略的代码中的一个简单错字。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-24
  • 1970-01-01
  • 2013-02-07
  • 1970-01-01
  • 2011-10-21
  • 1970-01-01
相关资源
最近更新 更多