字符串未被识别为有效的DateTime

本文关键字:有效 DateTime 识别 字符串 | 更新日期: 2023-09-27 17:58:49

我有一个搜索功能(由我的前任编写),它以日期范围、id和可用程序为输入,并在网格视图中显示结果。该功能在大多数情况下都很好(我已经测试过了),但对于我的应用程序的一个用户,它给出了这个错误消息。我无法自己复制这个错误来修复它。不知道出了什么问题!

你们能帮忙吗?

引发了类型为"System.Web.HttpUnhandledException"的异常。System.FormatException:字符串未被识别为有效的DateTime。在System.DateTimeParse.Parse(字符串s、DateTimeFormatInfo dtfi、DateTimeStyles样式)
在System.Convert.ToDateTime(字符串值)位于d:''SharedServices''APP''ViewFollowupWorkload.aspx中的APP_ViewFollowupWorkload.GetFilterString()。cs:line 1415
在d:''SharedServices''APP''ViewFollowupWorkload.aspx中的APP_ViewFollowupWorkload.Page_Load(对象发件人,EventArgs e)位于System.Web.Util.CaliHelper.EventArgFunctionCaller(IntPtr fp,Object o,Object 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上(布尔值包含同步点之前的阶段,布尔值包括同步点之后的阶段)
位于System.Web.UI.Page.HandleError(异常e)
在System.Web.UI.Page.ProcessRequestMain上(布尔值包含同步点之前的阶段,布尔值包括同步点之后的阶段)
在System.Web.UI.Page.ProcessRequest(布尔值包含同步点之前的阶段,布尔值包括同步点之后的阶段)
位于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_viewfollow-upworkload.aspx.ae7ca9bd.uwyek3vs.0中的ASP.app_viewfollow workload_aspx.ProcessRequest(HttpContext上下文)。cs:line 0
位于System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
在System.Web.HttpApplication.ExecuteStep(IExecutionStep步骤,Boolean和completedSynchronously)

以下是生成错误的.cs文件代码:

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)) + "''";
    }

字符串未被识别为有效的DateTime

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

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

尝试使用ParseExact-此处(MSDN).

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

您可以使用DateTime.ParseExact,如下所示

DateTime date = DateTime.ParseExact("25/12/2022", "dd/MM/yyyy", null);

DateTime date = DateTime.ParseExact("25/12/2022", "dd/MM/yyyy", CultureInfo.InvariantCulture);

第三个参数IFormatProvider指定区域性。如果字符串来自用户,您应该传递CultureInfo.CurrentCulture,否则为CultureInfo.InvariantCulture。CultureInfo.CurrentCulture将使用"区域选项"中的设置在用户指定的控制面板中。