vb.net 将 ASP.NET 文本框控件 .text 内容转换为日期/时间格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15853054/
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
Convert ASP.NET textbox control .text contents to Date/Time format
提问by adaam
I am trying to insert into a database - various details about an event. The asp.net textbox is using the Calendar Extender (so a little calendar pops up and fills the textbox with a correctly formatted date). The EventDate field in my Access database is of the type Date/Time. I need to convert the text/string to date/time format
我正在尝试插入数据库 - 有关事件的各种详细信息。asp.net 文本框正在使用日历扩展器(因此会弹出一个小日历并用正确格式的日期填充文本框)。我的 Access 数据库中的 EventDate 字段是日期/时间类型。我需要将文本/字符串转换为日期/时间格式
I have tried this so far:
到目前为止我已经尝试过这个:
VB:
VB:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim oleDbConn As New OleDb.OleDbConnection(ConfigurationManager.ConnectionStrings("BookMeetConnString").ConnectionString) Dim SqlString As String = "Insert into Events(EventTitle,EventDescription,EventDate,EventCategory) Values (@f1,@f2,@f3,@f4)" Dim cmd As OleDbCommand = New OleDbCommand(SqlString, oleDbConn) Dim strDate As String = tb_eventdate.Text Dim dtfi As New System.Globalization.DateTimeFormatInfo dtfi.ShortDatePattern = "dd/MM/yyyy" dtfi.DateSeparator = "/" Dim objDate As DateTime = Convert.ToDateTime(strDate, dtfi) cmd.CommandType = CommandType.Text cmd.Parameters.AddWithValue("@f1", tb_eventtitle.Text) cmd.Parameters.AddWithValue("@f2", tb_eventdescription.Text) cmd.Parameters.AddWithValue("@f3", tb_eventdate.Text) cmd.Parameters.AddWithValue("@f4", dd_eventcategory.Text) oleDbConn.Open() cmd.ExecuteNonQuery() System.Threading.Thread.Sleep("2000") Response.Redirect("~/calendar.aspx") End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim oleDbConn As New OleDb.OleDbConnection(ConfigurationManager.ConnectionStrings("BookMeetConnString").ConnectionString) Dim SqlString As String = "Insert into Events(EventTitle,EventDescription,EventDate,EventCategory) Values (@f1,@f2,@f3,@f4)" Dim cmd As OleDbCommand = New OleDbCommand(SqlString, oleDbConn) Dim strDate As String = tb_eventdate.Text Dim dtfi As New System.Globalization.DateTimeFormatInfo dtfi.ShortDatePattern = "dd/MM/yyyy" dtfi.DateSeparator = "/" Dim objDate As DateTime = Convert.ToDateTime(strDate, dtfi) cmd.CommandType = CommandType.Text cmd.Parameters.AddWithValue("@f1", tb_eventtitle.Text) cmd.Parameters.AddWithValue("@f2", tb_eventdescription.Text) cmd.Parameters.AddWithValue("@f3", tb_eventdate.Text) cmd.Parameters.AddWithValue("@f4", dd_eventcategory.Text) oleDbConn.Open() cmd.ExecuteNonQuery() System.Threading.Thread.Sleep("2000") Response.Redirect("~/calendar.aspx") End Sub
Here is my clientside code just for reference:
这是我的客户端代码,仅供参考:
<h1>Add An Event!<ajaxToolkit:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"> </ajaxToolkit:ToolkitScriptManager> </h1> <p>Title of Event: <asp:TextBox ID="tb_eventtitle" runat="server"></asp:TextBox> </p> <p>Event Description: <asp:TextBox ID="tb_eventdescription" runat="server"></asp:TextBox> </p> <p>Event Date: <asp:TextBox ID="tb_eventdate" runat="server"></asp:TextBox> <ajaxToolkit:CalendarExtender ID="tb_eventdate_CalendarExtender" runat="server" TargetControlID="tb_eventdate"> </ajaxToolkit:CalendarExtender> </p> <p>Event Category: <asp:DropDownList ID="dd_eventcategory" runat="server" DataSourceID="SqlDataSource1" DataTextField="CategoryTitle" DataValueField="CategoryTitle"> </asp:DropDownList> </p> <p> <asp:Button ID="Button1" runat="server" Text="Submit" /> </p>
<h1>Add An Event!<ajaxToolkit:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"> </ajaxToolkit:ToolkitScriptManager> </h1> <p>Title of Event: <asp:TextBox ID="tb_eventtitle" runat="server"></asp:TextBox> </p> <p>Event Description: <asp:TextBox ID="tb_eventdescription" runat="server"></asp:TextBox> </p> <p>Event Date: <asp:TextBox ID="tb_eventdate" runat="server"></asp:TextBox> <ajaxToolkit:CalendarExtender ID="tb_eventdate_CalendarExtender" runat="server" TargetControlID="tb_eventdate"> </ajaxToolkit:CalendarExtender> </p> <p>Event Category: <asp:DropDownList ID="dd_eventcategory" runat="server" DataSourceID="SqlDataSource1" DataTextField="CategoryTitle" DataValueField="CategoryTitle"> </asp:DropDownList> </p> <p> <asp:Button ID="Button1" runat="server" Text="Submit" /> </p>
When I try to fill out the form, I receive this error:
当我尝试填写表格时,收到此错误:


My Two questions are:
我的两个问题是:
- What is wrong with the code above, and how do I successfully use the DateTimeFormatInfo class to convert String to Date/Time?
- On a side note, the Calendar Extender inputs the date into the textbox in American Time format (MM/DD/YYYY), how do I change this to British (DD/MM/YYYY) format (I couldn't see an obvious property in the properties dialog to do this?)
- 上面的代码有什么问题,如何成功使用 DateTimeFormatInfo 类将字符串转换为日期/时间?
- 在旁注中,日历扩展器以美国时间格式 (MM/DD/YYYY) 将日期输入到文本框中,如何将其更改为英国 (DD/MM/YYYY) 格式(我看不到明显的属性在属性对话框中执行此操作?)
Thanks in advance for your answers!
预先感谢您的回答!
Adam
亚当
EDIT: Updated code below:
编辑:更新以下代码:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim oleDbConn As New OleDb.OleDbConnection(ConfigurationManager.ConnectionStrings("BookMeetConnString").ConnectionString) Dim SqlString As String = "Insert into Events(EventTitle,EventDescription,EventDate,EventCategory) Values (@f1,@f2,@f3,@f4)" Dim cmd As OleDbCommand = New OleDbCommand(SqlString, oleDbConn) cmd.CommandType = CommandType.Text cmd.Parameters.AddWithValue("@f1", tb_eventtitle.Text) cmd.Parameters.AddWithValue("@f2", tb_eventdescription.Text) cmd.Parameters.AddWithValue("@f3", DateTime.ParseExact(tb_eventdate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture)) cmd.Parameters.AddWithValue("@f4", dd_eventcategory.Text) oleDbConn.Open() cmd.ExecuteNonQuery() System.Threading.Thread.Sleep("2000") Response.Redirect("~/calendar.aspx") End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim oleDbConn As New OleDb.OleDbConnection(ConfigurationManager.ConnectionStrings("BookMeetConnString").ConnectionString) Dim SqlString As String = "Insert into Events(EventTitle,EventDescription,EventDate,EventCategory) Values (@f1,@f2,@f3,@f4)" Dim cmd As OleDbCommand = New OleDbCommand(SqlString, oleDbConn) cmd.CommandType = CommandType.Text cmd.Parameters.AddWithValue("@f1", tb_eventtitle.Text) cmd.Parameters.AddWithValue("@f2", tb_eventdescription.Text) cmd.Parameters.AddWithValue("@f3", DateTime.ParseExact(tb_eventdate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture)) cmd.Parameters.AddWithValue("@f4", dd_eventcategory.Text) oleDbConn.Open() cmd.ExecuteNonQuery() System.Threading.Thread.Sleep("2000") Response.Redirect("~/calendar.aspx") End Sub
采纳答案by Ivaylo Slavov
I'd recommend you use DateTime.ParseExactstatic method, especially this oveload:
我建议你使用DateTime.ParseExact静态方法,尤其是这个超载:
DateTime.ParseExact(textBox.Text, "dd/MM/yyyy",CultureInfo.InvariantCulture)
DateTime.ParseExact(textBox.Text, "dd/MM/yyyy",CultureInfo.InvariantCulture)
This will parse the text you have by the concrete format you specify ("dd/MM/yyyy"currently, case is importantsince mmis minutes as opposed to MMbeing months). Use of CultureInfo.InvariantCultureguarantees that date separators will be retrieved from the format string (the second parameter). I have noticed that if current culture is used, it overrides some aspects of the format string you pass to ParseExact.
这将按照您指定的具体格式解析您拥有的文本("dd/MM/yyyy"目前,大小写很重要,因为mm是分钟而不是MM月)。使用CultureInfo.InvariantCulture保证日期分隔符将从格式字符串(第二个参数)中检索。我注意到,如果使用当前区域性,它会覆盖您传递给的格式字符串的某些方面ParseExact。
A note on CultureInfo
关于 CultureInfo 的说明
Invariant culture is good also for the reason that your local dev environment may have different regional information setup than the deployment environment. Usually, .NET uses the current culturein all .ToStringcalls and implicit formatting or parsing. When forcing a format and culture invariance explicitly, you are less prone to problems you cannot reproduce locally but exist on the production application.
不变文化也很好,因为您的本地开发环境可能具有与部署环境不同的区域信息设置。通常,.NET在所有调用和隐式格式化或解析中使用当前区域性.ToString。明确强制格式和文化不变性时,您不太容易出现无法在本地重现但存在于生产应用程序中的问题。
A note on date/time formats
关于日期/时间格式的说明
With exact parsing, the datetime format is expected to strictlymatch the format of the input. You should then take into consideration the following examples:
通过精确解析,日期时间格式应与输入格式严格匹配。然后,您应该考虑以下示例:
ddmatches two-digit days only. So"dd/MM/yyyy"it will match"01/01/2013", but will fail for"1/1/2013"because it expects the exact number of digits for the day part. If you do not want leading zeros use:d/M/yyyyinstead. Single letter means one digit for days less than10and two digits for the others.MMmatches two-digit month, so all that applies toddvs.dis the same for months.yyyyexpects the year to be in 4 digits. If you use two-digit year, useyyinstead.
dd仅匹配两位数的天数。所以"dd/MM/yyyy"它会匹配"01/01/2013",但会失败,"1/1/2013"因为它期望当天部分的确切位数。如果您不想使用前导零,请使用:d/M/yyyy代替。单个字母表示少于天数的一位数,其他天10数的两位数。MM匹配两位数的月份,因此所有适用于ddvs.d的月份都是相同的。yyyy预计年份为 4 位数。如果您使用两位数年份,请yy改用。
A note on some ADO.NET providers
关于一些 ADO.NET 提供程序的说明
As it turns out to be the case with MS Access, the correctly parsed date-time object is not sufficient to make the query work. Currently, the following code
事实证明,MS Access 就是这种情况,正确解析的日期时间对象不足以使查询工作。目前,以下代码
cmd.Parameters.AddWithValue(...)
is used to add parameters to the query. However, this approach omits passing information to the ADO.NET db provider that tells what database type to use for the parameter. I have read on some forums that MS Access/OleDb is not capable to resolve the correct type in all cases. Therefore I recommend the following approach:
用于向查询添加参数。但是,此方法省略了将信息传递给 ADO.NET db 提供程序的信息,该信息告知参数使用的数据库类型。我在一些论坛上读到 MS Access/OleDb 无法在所有情况下解析正确的类型。因此,我推荐以下方法:
Dim prm as OleDbParameter = _
New OleDbParameter("@dateTimeParameterName", OleDbType.DateTime)
prm.Value = value 'value is an instance of `System.DateTime` parsed
'from the input
cmd.Parameters.Add(prm)
The above code allows to specify the parameter database type explicitly, so the OleDb driver is now capable of correctly passing the DateTimeobject to the MS Access database.
上面的代码允许显式指定参数数据库类型,因此 OleDb 驱动程序现在能够正确地将DateTime对象传递到 MS Access 数据库。
回答by Sedat Kumcu
I used below short code:
我使用了以下短代码:
//myDateValue is System.DateTime object.
OleDbCommand commandObject = new OleDbCommand();
...
commandObject.Parameters.Add(new OleDbParameter("@ADDED_DATE_PARAM", OleDbType.Date).Value = myDateValue);

