我通过此方法将日期从 WPF 发送到 ModelClass .......
private void buttonNTSave_Click(object sender, RoutedEventArgs e)
{
ModelClass model = new ModelClass();
model.TaskInsertion(textBoxNTSubject.Text, textBoxNTType.Text, Convert.ToDateTime(datePickerNT.SelectedDate), textBoxNTTitle.Text, textBoxNTDetail.Text);
}
此方法正在数据库中插入日期 ...
public void TaskInsertion(string subject, string type, DateTime dueDate, string title, string detail)
{
SqlConnection conn = new SqlConnection(connectionString);
try
{
string query = "INSERT INTO Tbl_Task (Email, Subject, Type, DueDate, Title, Detail) VALUES ('" + userEmail + "', '" + subject + "' , '" + type + "', '" + dueDate.Date + "', '" + title + "', '" + detail + "')";
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception e)
{
conn.Close();
}
}
但是,每当我尝试仅从数据库中检索日期到 DataGrid 时,仍然时间 日期正在展示..
public DataTable OverDueCurrentTask()
{
SqlConnection conn = new SqlConnection(connectionString);
try
{
DateTime DateToday = DateTime.UtcNow.Date;
string query = "DECLARE @sDate Date SET @sDate = '" + DateToday.Date + "' SELECT Title, Subject, Type, DueDate FROM Tbl_Task WHERE DueDate >= @sDate";
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
cmd.ExecuteNonQuery();
SqlDataAdapter dataAdp = new SqlDataAdapter(cmd);
DataTable dataTbl = new DataTable("Tbl_Task");
dataAdp.Fill(dataTbl);
dataAdp.Update(dataTbl);
return dataTbl;
}
catch (Exception e)
{
conn.Close();
return null;
}
}
如何在不显示时间的情况下显示日期? 注:在数据库中,DueDate是日期类型列。
答案 0 :(得分:0)
我相信你也可以在C#中做到这一点。在SQL查询中,您可以使用:
select cast([date] as date) as dateonly
将datetime
转换为date
。
以下编辑由Dan Guzman提供:
构建应用程序所需的查询字符串的C#代码是:
string query = "DECLARE @sDate Date SET @sDate = '" + DateToday.Date + "' SELECT Title, Subject, Type, CAST(DueDate AS date) AS DueDate FROM Tbl_Task WHERE DueDate >= @sDate;";
答案 1 :(得分:0)
您需要投放DueDate
列cast([DueDate] as date) > = @sDate
。虽然sDate
已被声明为date
。
string query = @"DECLARE @sDate Date SET @sDate = '" + DateToday.Date + "'
SELECT Title, Subject, Type, cast([DueDate] as date) as DueDate FROM Tbl_Task
WHERE cast([DueDate] as date) >= @sDate";
虽然它完成了答案,但您需要对代码进行细微更改,以避免SQL注入攻击。使用SqlCommand Parameters。在代码中添加using
块。