我正在尝试通过从具有各种掩码等的文本框中获取值来将日期时间添加到数据库表中。我收到以下错误:
String was not recognized as a valid DateTime.
文本框代码:
<asp:TableRow>
<asp:TableCell>
<asp:ToolkitScriptManager ID="calendarToolkit" runat="server"></asp:ToolkitScriptManager>
<asp:TextBox ID="startDateTextbox" runat="server"></asp:TextBox>
<asp:CalendarExtender Format="yyyy-dd-MM" ID="startDateExtender" TargetControlID="startDateTextbox" runat="server" />
</asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell>
<asp:TextBox ID="startTimeTextbox" runat="server"></asp:TextBox>
<asp:MaskedEditExtender ID="m1" runat="server" Mask="99:99" MaskType="Time" AcceptAMPM="false"
MessageValidatorTip="true" TargetControlID="startTimeTextbox"
ClearMaskOnLostFocus="false">
</asp:MaskedEditExtender>
<asp:MaskedEditValidator ID="mv1" runat="server" ControlExtender="m1" ControlToValidate="startTimeTextbox"
Display="none" EmptyValueMessage="Time is required" InvalidValueMessage="Valid Start Time"
IsValidEmpty="true" TooltipMessage="Input a time">
</asp:MaskedEditValidator>
</asp:TableCell>
</asp:TableRow>
c#代码将值添加到数据库中:
string sqlQuery =
"insert into dbo.Event_Info(event_name, description, location, date_end,date_start,image_url) values(@name, @desc, @location,@startDate,@endDate,@imageURL)";
SqlConnection dbConnection = new SqlConnection("server=(local)\\SGSQL;database=STEvent;Trusted_Connection=yes");
dbConnection.Open();
SqlCommand dbCommand = new SqlCommand(sqlQuery, dbConnection);
SqlParameter startParam = new SqlParameter("@startDate",SqlDbType.DateTime);
startParam.Value = Convert.ToDateTime(startDateTextbox.Text +" " + startTimeTextbox.Text);
dbCommand.Parameters.Add(startParam);
dbCommand.ExecuteNonQuery();
dbConnection.Close();
注意:只添加了代码的一个子集,因为显示所有其他参数似乎冗长且多余。
答案 0 :(得分:3)
尝试将String
解析为DateTime
。
// String to DateTime
String MyString;
MyString = "1999-09-01 21:34 PM";
//MyString = "1999-09-01 21:34 p.m."; //Depends on your regional settings
DateTime MyDateTime;
MyDateTime = new DateTime();
MyDateTime = DateTime.ParseExact(MyString, "yyyy-MM-dd HH:mm tt",
null)
答案 1 :(得分:1)
日期格式&#34; yyyy-dd-MM&#34;是无效的。你可以查找&#34;转换&#34; SQL Server文档中的函数用于有效格式。
&#34; YYYY-MM-DD&#34;是一个很好的解决方案