在提交到存储过程参数之前转换为所需的日期格式
在文本框中,用户以 dd/MM/yyyy 格式输入日期。我将此值发送到存储过程:
cmd.Parameters.AddWithValue("@myDate", Convert.ToDateTime(txtMyDate.Text));
存储过程参数的类型为 SmallDateTime。我想以 dd/MM/yyyy 格式传递上述代码值。如何在上面的代码中指定格式以确保 SQL Server 以 dd/MM/yyyy 格式存储日期?
In a TextBox, user enters date in the format dd/MM/yyyy format. I am sending this value to stored procedure as:
cmd.Parameters.AddWithValue("@myDate", Convert.ToDateTime(txtMyDate.Text));
The stored procedure parameter is of the type SmallDateTime. I want to pass the above code value in dd/MM/yyyy format. How to specify the format in the above code to make sure that SQL Server stores dates in dd/MM/yyyy format?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您所描述的内容有点令人困惑:
如果存储过程的参数确实是 SmallDataTime 那么它本质上没有格式。
txtMyDate.Text
似乎是一个字符串,因此具有日期格式...您可以本地化友好并保持代码原样 - 至少在普通的桌面应用程序中它会考虑到日期格式的系统设置。另一种选择是显式硬编码格式,以便用户输入必须采用这种特定格式...这可以通过使用 DateTime.ParseExact ( txtMyDate.Text, "dd/MM/yyyy", CultureInfo.不变文化)。MSDN 参考:
What you describe is a bit confusing:
IF the parameter of the Stored Procedure is indeed SmallDataTime then it inherently has no format.
txtMyDate.Text
seems to be a string and thus have a dateformat... you can either be localizetion-friendly and keep your code as it is - at least in a normal desktop app it would take into account the system setting for dateformat. Another option is to explicitely hardcode the format so that the user input has to be in this specific format... this can be done by usingDateTime.ParseExact ( txtMyDate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture )
.MSDN references: