首页 > 解决方案 > 将字符串解析为日期时间的问题 - 字符串未被识别为有效的日期时间

问题描述

我在将字符串解析为 datime 时遇到了一些问题。我正在比较日期是否小于现在的日期,然后为 Gridview 中的单元格提供另一个背景。

 protected void TabulkaZakazkyAktivni_DataBound1(object sender, GridViewRowEventArgs e)
 {
    if (gvr.RowType == DataControlRowType.DataRow)
    {
        if (DateTime.ParseExact((gvr.Cells[11].Text), "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture) < DateTime.Now)
        {
            gvr.Cells[11].BackColor = System.Drawing.Color.Red;
            Label2.Text = Convert.ToString(gvr.Cells[11].Text);
        }
    }

}

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

编辑 1:内部 gvr.Cells[11] 是“2019-05-19 10:19:48.000”

标签: c#

解决方案


试试这个方法:

protected void TabulkaZakazkyAktivni_DataBound1(object sender, GridViewRowEventArgs e)
{
    if (gvr.RowType == DataControlRowType.DataRow)
    {
        if (DateTime.Parse(gvr.Cells[11].Text) < DateTime.Now)
        {
            gvr.Cells[11].BackColor = System.Drawing.Color.Red;
            Label2.Text = Convert.ToString(gvr.Cells[11].Text);
        }
    }
}

推荐阅读