从SQL数据库读取DateTime值



如何从SQL数据库读取DateTime字段?

这不起作用:

emp.DateFacturation = (DateTime)(dr["DateFacturation"])

也不是:

emp.DateFacturation = DateTime.Parse(dr["DateFacturation"].toString());

由于您已经评论了现在已删除的答案:

DR是DataReader

您可以使用SqlDataReader.GetDateTime。您应该首先检查该值是否为DBNullDataReader.IsDBNull

DateTime dateFacturation;
int colIndex = dr.GetOrdinal("DateFacturation");
if(!dr.IsDBNull( colIndex ))
    dateFacturation = dr.GetDateTime( colIndex );

我使用GetOrdinal获取列名的列索引将其传递给GetDateTime

使用 DateTime.TryParse

DateTime datevalue;
if (DateTime.TryParse(dr["DateFacturation"].ToString(), out datevalue))
{
    emp.DateFacturation = datevalue;              
}
else
{
    // TODO: conversion failed... not a valid DateTime
    // Print it out and see what is wrong with it...
}

最新更新