如何通过 C# ASP.net 从 SQL Server 中的文本框中存储日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16519956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to store date from text box in SQL Server through C# ASP.net
提问by Nils
I am having trouble while storing date in sql server DB through C# asp.net, online
我在通过 C# asp.net 在线将日期存储在 sql server DB 中时遇到问题
I have used asp Text box and asp calender extender in ASP file to get date from user,
我在 ASP 文件中使用了 asp 文本框和 asp 日历扩展器来从用户那里获取日期,
<asp:TextBox runat="server" ID="txt_date"></asp:TextBox>
<asp:CalendarExtender runat="server" ID="cal_date" TargetControlID="txt_date"></asp:CalendarExtender>
code behind file is, assume connection and command are declared and initialized ,
文件背后的代码是,假设连接和命令已声明并初始化,
mycom = new SqlCommand("insert into mytable(dtCol1) values('"+Convert.ToDateTime(txt_dob.Text).ToString("dd-MMM-yyyy") + "')", mycon);mycom.ExecuteNonQuery();
Problem is, when I select date less than 12 of any month it works perfect, but when date/day is greater than 12 of any month it gives error,
问题是,当我选择任何一个月的小于 12 的日期时,它工作得很好,但是当日期/天大于任何一个月的 12 时,它会出错,
Exception Details: System.FormatException: String was not recognized as a valid DateTime.
I have tried all combinations of .ToString("dd-MMM-yyyy")
我已经尝试了 .ToString("dd-MMM-yyyy") 的所有组合
Please Help thanks in advance
请帮助提前致谢
采纳答案by Rajeev Kumar
Try this
尝试这个
CultureInfo provider = CultureInfo.InvariantCulture;
System.Globalization.DateTimeStyles style = DateTimeStyles.None;
DateTime dt;
DateTime.TryParseExact(txt_dob.Text, "m-d-yyyy", provider, style, out dt);
mycom = new SqlCommand("insert into mytable(dtCol1) values(@datevalue)", mycon);
cmd.Parameters.Add("@datevalue",SqlDbType.DateTime).Value =dt;
mycom.ExecuteNonQuery();
回答by Altaf Sami
Use this:
用这个:
mycom = new SqlCommand("insert into mytable (dtCol1) values ('" + Convert.ToDateTime(txt).ToString("MMM-dd-yyyy") + "')", mycon);
Thanks
谢谢
回答by Ivaylo Slavov
The problem seems to come from here: Convert.ToDateTime(txt_dob.Text). This type of conversion is not good because:
问题似乎来自这里:Convert.ToDateTime(txt_dob.Text)。这种类型的转换不好,因为:
It disregards the format that the control uses.
Convert.ToDateTime(...)expects the string to be in a certain format(s) in order to parse it correctly. This cannot handle any custom formats that thetxt_dobcould use.It is ignorant of culture-specific formatting.Internally,
Convert.ToDateTime(...)will probably stick toCultureInfo.CurrentCulture, which is not said to be capable of parsing the date. Also, some front-end controls in .NET recognize and use the client culture passed by the browser (for web apps), and it is likely for that culture to be different than the server culture.CultureInfo.CurrentCulturewill represent the server-side culture and formatting discrepancies are possible to occur
它不考虑控件使用的格式。
Convert.ToDateTime(...)期望字符串采用某种格式以便正确解析它。这无法处理txt_dob可以使用的任何自定义格式。它不知道特定于文化的格式。在内部,
Convert.ToDateTime(...)可能会坚持CultureInfo.CurrentCulture,据说不能解析日期。此外,.NET 中的一些前端控件识别并使用浏览器传递的客户端文化(对于 Web 应用程序),并且该文化可能与服务器文化不同。CultureInfo.CurrentCulture将代表服务器端文化,并且可能会出现格式差异
If you know the format of the txt_dob.Textyou have to explicitly parse it. In the example below I have assumed the format is "MM/dd/yyyy":
如果您知道 的格式,则txt_dob.Text必须明确解析它。在下面的示例中,我假设格式为"MM/dd/yyyy":
String dateFormat = "MM/dd/yyyy";//The format that the txt_dob control uses
DateTime parsedDate = DateTime.ParseExact(
txt_dob.Text, dateFormat, CultureInfo.InvariantCulture);
You can also check this related topicwith some additional information on a similar case like yours
您还可以查看此相关主题以及有关类似案例的一些附加信息
回答by Sain Pradeep
User DateTime.ParseExact() in place of Convert.ToDateTime() method.
用户 DateTime.ParseExact() 代替 Convert.ToDateTime() 方法。
dateString = "12-31-2012";
format = "MM-dd-yyyy";
try
{
DateTime result = DateTime.ParseExact(dateString, format, CultureInfo.CurrentCulture);
}
catch (FormatException)
{
}
回答by Pure.Krome
TLDR; You're using the wrong DateTime format.
TLDR;您使用了错误的 DateTime格式。
There's plenty of issues here that will blow up Death Stars, left right and center.
这里有很多问题会炸毁死星,左右和中间。
Firstly, you're creating the sql query on the fly - that's probably the biggest no-no in the last 10 years and everyone has stopped doing that. In other words, please please please don't start doing (the very out of date) ADO.NET programming to pass data from the website to the database. Modern replacements like Entity Framework, NHibernate or even Linq2Sql if you're desperate.
首先,您正在即时创建 sql 查询 - 这可能是过去 10 年中最大的禁忌,并且每个人都已停止这样做。换句话说,请不要开始做(非常过时的)ADO.NET 编程来将数据从网站传递到数据库。如果您不顾一切,可以使用现代替代品,如实体框架、NHibernate 甚至 Linq2Sql。
Ok - that said, lets try and answer your question none-the-less.
好的 - 就是说,让我们试着回答你的问题。
The reason is because u're passing in the values in the wrong format. You're doing dates first. Your sql server is probably wanting it to be MONTHS first. Because it's probably been setup to be style 121(<-- that's a real technical sql server setting thing for Compatibility crap..)
原因是因为您以错误的格式传递值。你先约会。您的 sql server 可能希望它首先是 MONTHS。因为它可能已设置为样式 121(<-- 这是兼容性废话的真正技术 sql server 设置内容..)
But don't try and fight and guess.
但不要试图打架和猜测。
Lets use a more universal and start string format: yyyy-mm-dd hh:mm:ss.ms
让我们使用更通用的起始字符串格式:yyyy-mm-dd hh:mm:ss.ms
eg.
例如。
SELECT CAST('2013-02-08 09:53:56.223' as DateTime)
And you can see this in action over at SQLFIDDLE.
This is a really good StackOverflow questionthat explains what the default DateTime format is, etc.
这是一个非常好的 StackOverflow 问题,它解释了默认的 DateTime 格式是什么等。
回答by Feras Salim
try this
尝试这个
mycom = new SqlCommand("insert into mytable(dtCol1) values(@value1)");
mycom.Parameters.AddWithValue("@value1",Convert.ToDateTime(txt_dob.Text));
mycom.ExecuteNonQuery();
回答by Hazem Elkady
[Date_Of_Birth]='" + Convert.ToDateTime(TxtDate_Of_Birth.Text).ToString("MM-dd-yyyy") + "'
[Date_Of_Birth]='" + Convert.ToDateTime(TxtDate_Of_Birth.Text).ToString("MM-dd-yyyy") + "'
Will help the cause of error that sqlserver accepts datetime in format MM/dd/yyyy, but not in dd/MM/yyyy.
将有助于 sqlserver 接受格式中的日期时间MM/dd/yyyy而不是dd/MM/yyyy.

