String.Format无法处理日期

时间:2015-09-17 14:42:36

标签: c# asp.net date dataset string.format

我正在执行一个sql查询并将其存储在数据集中,从那里我发送一封电子邮件,一切都按预期工作,除了这个时间附加到日期12:00:00 Am,它看起来真的很奇怪电子邮件,我知道这是因为该列的数据类型是日期,它附加的对象将其存储为datetime,因此被重置为午夜但我直接查询sql并从数据表中检索值但它仍然有附在它上面的时间。无论如何要解决这个问题我尝试了下面但它不会工作:

string conn = ConfigurationManager.ConnectionStrings["WorkOrderConnectionString3"].ToString();
SqlConnection sqlconn = new SqlConnection(conn);
cmd.Connection = sqlconn;
sqlconn.Open();
cmd.CommandType = CommandType.Text;
String getdatasql = "SELECT WorkOrderNum, Requestor, Date, Department, CompletionDate, MachineDescription, MachineLocation," +
"[Type of Work Order], [Work Required], [WorkPerformed / PartsUsed], [Work Completed By :], [Maint. Supv. Approval]," +
" [Work Comp Date], [Supv Approval Date], Status, [Maint. Supv. Approval Date]" +
"FROM Master WHERE ([Type of Work Order] = N'General') AND (WorkOrderNum = @rockbottom) AND Status = 'Complete' ORDER BY WorkOrderNum DESC";
cmd.CommandText = getdatasql;
cmd.Parameters.AddWithValue("@rockbottom", TextBox10.Text);
SqlDataAdapter getdata = new SqlDataAdapter(cmd);
DataSet ds1 = new DataSet();
showdata.Fill(ds1);
string WorkOrderNum = ds1.Tables[0].Rows[0]["WorkOrderNum"].ToString();
string Requestor = ds1.Tables[0].Rows[0]["Requestor"].ToString();
string Date = ds1.Tables[0].Rows[0]["Date"].ToString();
String date = String.Format("{0:MM/d/yyyy}", Date);
cmd.ExecuteNonQuery();

当我进行调试时,我得到了这个:

enter image description here

在我的电子邮件中,它看起来像这样:

enter image description here

尝试解决方案仍然有时间:

enter image description here

搞定了工作:)

enter image description here

1 个答案:

答案 0 :(得分:10)

这是问题所在:

string Date = ds1.Tables[0].Rows[0]["Date"].ToString();

您的Date变量已经是一个字符串,因此尝试将其格式设置为DateTime不会起作用。你想要这样的东西:

DateTime Date = (DateTime) ds1.Tables[0].Rows[0]["Date"];

...虽然我建议不要使用名为Date的局部变量,尤其是在范围内使用名为date的变量...