【问题标题】:String was not recognized as a valid DateTime字符串未被识别为有效的 DateTime
【发布时间】:2011-09-12 19:32:40
【问题描述】:

我有一个搜索功能(由我的前任编写),它将日期范围、ID、可用程序作为输入并在网格视图中显示结果。该功能在大多数情况下都可以正常工作(我已经对其进行了测试),但是对于我的应用程序的一位用户,它给出了此错误消息。我无法自己重现此错误以修复它。不知道怎么回事!

你们能帮忙吗?

引发了“System.Web.HttpUnhandledException”类型的异常。 System.FormatException:字符串未被识别为有效的 DateTime。 在 System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles 样式)
在 System.Convert.ToDateTime(字符串值) 在 d:\SharedServices\APP\ViewFollowupWorkload.aspx.cs:1415 行中的 APP_ViewFollowupWorkload.GetFilterString()
在 APP_ViewFollowupWorkload.Page_Load(Object sender, EventArgs e) in d:\SharedServices\APP\ViewFollowupWorkload.aspx.cs:line 268
在 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp,对象 o,对象 t,EventArgs e)
在 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(对象发送者,EventArgs e)
在 System.Web.UI.Control.OnLoad(EventArgs e)
在 System.Web.UI.Control.LoadRecursive()
在 System.Web.UI.Page.ProcessRequestMain(布尔 includeStagesBeforeAsyncPoint,布尔 includeStagesAfterAsyncPoint)
在 System.Web.UI.Page.HandleError(异常 e)
在 System.Web.UI.Page.ProcessRequestMain(布尔 includeStagesBeforeAsyncPoint,布尔 includeStagesAfterAsyncPoint)
在 System.Web.UI.Page.ProcessRequest(布尔 includeStagesBeforeAsyncPoint,布尔 includeStagesAfterAsyncPoint)
在 System.Web.UI.Page.ProcessRequest()
在 System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext 上下文) 在 System.Web.UI.Page.ProcessRequest(HttpContext 上下文)
在 c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\bad754dd\a11f74ff\App_Web_viewfollowupworkload.aspx.ae7ca9bd.uwyek3vs.0.cs 中的 ASP.app_viewfollowupworkload_aspx.ProcessRequest(HttpContext context):第 0 行
在 System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
在 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

这是产生错误的.c​​s文件代码:

if (txtDateTo.ToString() != string.Empty)
        {
            if (txtDateTo.ToString().Length > 2)
                strFilter = strFilter + " AND submission_date <= ''" + Convert.ToString(Convert.ToDateTime(txtDateTo.ToString()) + new TimeSpan(1, 0, 0, 0)) + "''";

    }

【问题讨论】:

  • 尝试记录日期,让用户施展魔法。或者,用 try/catch 包围它并将堆栈 tace + 用户输入发送到您的邮件。然后,您会在下次发生错误时收到通知,并获得错误日期。

标签: c# asp.net datetime message


【解决方案1】:

错误表明txtDateTo 的传入值不是有效的DateTime - 比如32/11/2011

您可以使用DateTime.TryParse 重载之一将代码更改为不会引发异常的代码。这不会解析无效值,但会避免引发异常 - 您仍然需要确定在这种情况下该怎么做。

【讨论】:

  • 同意,但由于这是用户输入的值,我建议将CompareValidatorCompareValidator.Operator = "DataTypeCheck"CompareValidator.Type = "Date" 一起使用,以防止用户输入无效的日期字符串。不要忘记实现服务器端验证。
【解决方案2】:

尝试改用 ParseExact - 这里 (MSDN) .

也许他们使用了一些不寻常的日期时间格式。询问您的用户文本框中的哪个值用于转换为日期时间。

【讨论】:

    猜你喜欢
    • 2021-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多