如何将C#now与SQL Server datetime进行比较

问题描述 投票:0回答:1

你如何将C#现在与SQL Server日期时间进行比较?

我尝试了十件事,但没有任何作用:

string sql;
DataTableReader dr;
sql = "Select StartDate from mytable";

SqlDataAdapter da = new SqlDataAdapter(sql, ConfigurationManager.AppSettings["DB"]);
DataTable dt = new DataTable();
da.Fill(dt);

dr = dt.CreateDataReader();

var now = DateTime.Now.Date;

while (dr.Read())
{
    // StartDate datatype is a SQL Server datetime and possibly can be null
    if(dr["StartDate"] < now) 
    {
        // code for start date is in the past
    }
}
c# asp.net sql-server
1个回答
3
投票

您必须将SQL Server字符串转换为datetime。

// StartDate datatype is a SQL Server datetime and possibly can be null
if(Convert.ToDateTime(dr["StartDate"]) < now) 
{
    // code for start date is in the past
}
© www.soinside.com 2019 - 2024. All rights reserved.