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

时间:2015-12-03 06:58:48

标签: c#

当我的某个列的数据表中包含空值时,我收到了此异常。假设我想要允许空值或类似的东西,我该如何解决这个问题?

  

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

这是我的代码。

     foreach (DataRow row in ds.Tables[0].Rows)
                {
     row["Effective_Period"] = Convert.ToDateTime(row["Effect_Date_From"].ToString()).ToString("dd/MM/yyyy") 
+ " - " +  Convert.ToDateTime(row["Effect_Date_To"].ToString()).ToString("dd/MM/yyyy");
    }

在我的ds.Table中,这是我的专栏

----------------------
Effective_Period
---------------------
10/2/2012 - 20/3/2012
---------------------

---------------------

---------------------

6 个答案:

答案 0 :(得分:1)

可能的解决方案:

foreach (DataRow row in ds.Tables[0].Rows)
{
    DateTime effectiveDateFrom;
    DateTime effectiveDateTo;

    if (!DateTime.TryParse(row["Effect_Date_From"], out effectiveDateFrom)
        effectiveDateFrom = DateTime.MinValue;

    if (!DateTime.TryParse(row["Effect_Date_To"], out effectiveDateTo)
        effectiveDateTo = DateTime.MinValue;

    row["Effective_Period"] = effectiveDateFrom.ToString("dd/MM/yyyy") + " - " +  effectiveDateTo.ToString("dd/MM/yyyy");
}

答案 1 :(得分:0)

您可能希望在DateTime定义的C#表示中反映可为空的选项:

Nullable<DateTime> value;
// or
DateTime? value;

两种形式都是等同的。

当然,在使用C#中的值时,您必须定义null上要执行的操作,并且不能依赖某些魔法null.ToString()进行转换。

您可能还想查看this question。精华:使用row.Field<DateTime?>("Effect_Date_From")从数据行中获取可为空的DateTime

答案 2 :(得分:0)

如果要允许NULL,请在数据库表中将该字段设为NULLABLE。然后,它将允许插入NULL值而不会出现任何问题。

此外,如果您想允许显示的值,则必须将字段设为nvarchar,因为这不会被识别为有效DateTime

另一个重要的注意事项,不是像这样存储,而是可以轻松地为from-to期间创建两个单独的列,并分别在两个列中存储DateTime值。这样,您还可以根据所需日期查询数据和过滤数据。

更新:

如果您传递NULL并使用.ToString(),您也会收到此例外。因此,在使用.ToString()之前,请确保您在这里传递了一些内容,无论是日期还是字符串。在后端,您可以根据需要修改数据类型。

这里要做的一件好事就是在使用.ToString()进行转换之前实现空检查。如果为null,您可以直接传递null,如果不是,你可以转换价值,然后传递。

希望这有帮助。

答案 3 :(得分:0)

使用DateTime.TryParse可以帮助您检查是否存在无效日期,并相应地改变您的业务逻辑。

https://msdn.microsoft.com/en-us/library/system.datetime.tryparse(v=vs.110).aspx

答案 4 :(得分:0)

尝试:

 foreach (DataRow row in ds.Tables[0].Rows)
            {
                bool fromIsNull = DBNull.Value.Equals(row["Effect_Date_From"]);
                bool toIsNull = DBNull.Value.Equals(row["Effect_Date_To"]);
                row["Effective_Period"] = (fromIsNull ? string.Empty : Convert.ToDateTime(row["Effect_Date_From"].ToString()).ToString("dd/MM/yyyy"))
                    + (fromIsNull || toIsNull ? string.Empty : " - " )
                    + (toIsNull ? string.Empty : Convert.ToDateTime(row["Effect_Date_To"].ToString()).ToString("dd/MM/yyyy"));
            }

更新了代码以适应您的上一条评论。这就是你隐藏/显示“ - ”的方式。但这完全取决于你想如何处理这个案子。

答案 5 :(得分:0)

Null没有ToString()函数,因此如果您希望结果为null,则必须确保不会在其上调用函数。