3

我正在尝试通过从具有各种掩码等的文本框中获取值来将日期时间添加到数据库表中。我收到以下错误:

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();

注意:只添加了代码的一个子集,因为显示所有其他参数似乎很长而且多余。

4

2 回答 2

3

尝试解析你的Stringto 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)
于 2012-12-05T12:21:51.230 回答
1

日期格式“yyyy-dd-MM”无效。您可以在 SQL Server 文档中查找“转换”函数以获取有效格式。

“yyyy-MM-dd”是一个很好的解决方案

于 2012-12-05T12:21:16.667 回答