我正在使用ASP.NET(C#)和SQLServer 2008开发一个应用程序。在我的数据库中,我有一个字段DepositDate,数据类型是“DATE”。在我的数据输入表单上,我根据用户要求使用jquery datepicker及其在文本框中的返回日期作为dd / mm / yyyy格式,而我在数据库中注意到它的保留日期值为yyyy-mm-dd..i我很困惑。
保存记录时,由于唯一可用的转换格式为Convert.ToDateTime,而我的数据要求仅为DATE,因此我没有获得有效的日期时间。
有人可以提出解决方法如何处理它。?
DateTime thedate = DateTime.Parse(txt_IDate.Text);
DateTime mdate = DateTime.Parse(txt_Mdate.Text);
db.AddInParameter(cmd, "@SIssueDate", System.Data.DbType.Date);
db.SetParameterValue(cmd, "@SIssueDate", thedate.ToShortDateString());
db.AddInParameter(cmd, "@SMaturityDate", System.Data.DbType.DateTime);
db.SetParameterValue(cmd, "@SMaturityDate", mdate.ToShortDateString());
答案 0 :(得分:3)
为什么首先将参数值设置为 strings ?只需使用DateTime
值本身:
db.AddInParameter(cmd, "@SIssueDate", DbType.Date);
db.SetParameterValue(cmd, "@SIssueDate", thedate);
db.AddInParameter(cmd, "@SMaturityDate", DbType.DateTime);
db.SetParameterValue(cmd, "@SMaturityDate", mdate);
我怀疑您的数据库是以任何特定字符串格式存储值...它们不是字符串,它们是日期。这就像询问数据库是否存储十六进制或十进制格式的整数......它只是存储数字。
基本上,您需要以适当的格式解析用户的输入数据(可能是您已经在做的),然后在获取时再次格式化。除了表示层之外,您应该只将认为作为日期值,而不使用任何相关格式。
想象来自不同国家/地区的两位用户可能会有所帮助,每位用户都会查看日期列表。各自希望以适合其文化的格式查看这些日期 - 因此他们可能会看到不同的表示,但他们会看到相同的实际日期。
答案 1 :(得分:-2)
如果这适合你,你可以像thedate.ToString(“yyyy-MM-dd”)那样做,你只会得到2011-01-20