cmd.Parameters.Add(“@ StartDate”,SqlDbType.DateTime).Value = DateTime.Parse(txtStartDate.Text);
txtStartDate.Text中的值类似于31-07-2012
我需要将其作为2012-07-31。
用于处理storedprocedure。
我的代码就像:
cmd = new SqlCommand("DownloadtoXLSheet", conn);
cmd.Parameters.Add("@StartDate", SqlDbType.DateTime).Value = DateTime.Parse(txtStartDate.Text);
cmd.Parameters.Add("@EndDate", SqlDbType.DateTime).Value = DateTime.Parse(txtEndDate.Text);
cmd.Parameters.Add("@FirstName", SqlDbType.VarChar).Value = DropDownList1.Text.ToString();
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt1);
帮帮我
答案 0 :(得分:3)
首先,您不需要特定格式的日期来在存储过程/数据库中进行处理。将DateTime添加为参数(类型为DateTime)后,SQL提供程序将确保SQL Server可以处理日期。
另一方面,您可能需要DateTime.Parse的特定格式的日期才能工作。
尝试:
DateTime.ParseExact(input, "dd-MM-yyyy", CultureInfo.InvariantCulture);
但是,也许您应该使用DateTime.TryParseExact
来避免例外?
答案 1 :(得分:2)
使用DateTime.ParseExact
方法代替DateTime.Parse
。
DateTime result=DateTime.ParseExact("31-07-2012", "dd-MM-yyyy",CultureInfo.InvariantCulture);
答案 2 :(得分:0)
尝试
DateTime dt = ...;
dt.ToString("yyyy-MM-dd");
答案 3 :(得分:0)
在.ToString()方法中,您可以指定格式字符串 http://msdn.microsoft.com/en-us/library/zdtaw1bw.aspx
DateTime.Parse(txtStartDate.Text).ToString("yyyy-MM-dd")