比较所选日期和数据库日期

时间:2019-04-04 04:10:39

标签: c# asp.net sql-server date

我的逻辑是:

”如果所选日期与Holiday表中的数据库日期匹配,则返回消息为“确定”

我已经在下面的代码中格式化了日期。当我使用硬编码的数据库日期进行测试时,代码可以正常工作。

如何从我的Holiday表中获取数据库日期?

PS:Holiday表包含不同的日期,因此系统需要循环搜索Holiday表中的每一行。

代码:

[System.Web.Services.WebMethod]
public static string GetDateFromDB(DateTime compareDate)
{      
    string selectedDate = compareDate.ToString("yyyy/MM/dd");   

    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["LoginDBConnectionString1"].ConnectionString);
    SqlCommand com = new SqlCommand("SELECT * from Holiday", conn);
    SqlDataAdapter sqlDa = new SqlDataAdapter(com);
    DataTable dt = new DataTable();
    sqlDa.Fill(dt);

    //hardcoded is ok 
    string dbDateString = "2019-02-20";
    DateTime date1 = DateTime.ParseExact(dbDateString.Split(' ')[0], "yyyy/MM/dd", null);           
    string dateDB = date1.ToString("yyyy/MM/dd");

    if (dateDB == selectedDate)
    {     
        return "OK";
    }
    else
    {
        return "NG";
    }          
}

2 个答案:

答案 0 :(得分:0)

string selectedDate = compareDate.ToString("yyyy/MM/dd");   

    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["LoginDBConnectionString1"].ConnectionString);
    SqlCommand com = new SqlCommand("SELECT * from Holiday where Date='" + selectedDate + "'", conn);
    SqlDataAdapter sqlDa = new SqlDataAdapter(com);
    DataTable dt = new DataTable();
    sqlDa.Fill(dt);

if (dt == null || dt.Rows.Count() == 0)
    return "NG";
else
    return "OK";

答案 1 :(得分:0)

您说您有多行,因此您可以在循环所有行后返回“ OK”或“ NG”(或在出现错误时中断):

[System.Web.Services.WebMethod]
public static string GetDateFromDB(DateTime compareDate)
{      
    string selectedDate = compareDate.ToString("yyyy/MM/dd");   

    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["LoginDBConnectionString1"].ConnectionString);
    SqlCommand com = new SqlCommand("SELECT * from Holiday", conn);
    SqlDataAdapter sqlDa = new SqlDataAdapter(com);
    DataTable dt = new DataTable();
    sqlDa.Fill(dt);

    if (dt != null && dt.Rows.Count > 0)
    {
        string formatDate = "yyyy/MM/dd";
        foreach (DataRow dr in dt.Rows)
        {
            string dateString = dr["yourColumnName"].ToString();
            if (string.IsNullOrEmpty(dateString))
            {
                continue; // Or set error or something
            }

            dateString = DateTime.ParseExact(dateString.Split(' ')[0], formatDate, null).ToString(formatDate);
            if (dateString.Equals(compareDate))
            {
                // Do something
            }
            else
            {
                // Set error message or something
            }
        }

        // Check after loop and return "OK" or "NG"
    }     
}