在插入数据库之前将字符串转换为小日期时间

本文关键字:转换 日期 时间 字符串 插入 数据库 | 更新日期: 2023-09-27 18:31:20

我把所有东西都插入得很好,直到我尝试将字符串"09/21/3013"插入到到达日期列中,这是一个小日期时间。如何转换它以便我可以插入到数据库中?提前感谢!

代码如下:

    private void ExecuteInsert(string BookingName, string BookedBy)
{
    string connString = System.Configuration.ConfigurationManager.ConnectionStrings["CateringAuthorizationEntities"].ConnectionString;
    SqlConnection conn = new SqlConnection(connString);
    string sql = "INSERT INTO tbBooking (BookingName, BookedBy, ArrivalDate) VALUES "
                + " (@BookingName, @BookedBy, @ArrivalDate)";
    try
    {
        conn.Open();
        SqlCommand cmd = new SqlCommand(sql, conn);
        SqlParameter[] param = new SqlParameter[3];
        //param[0] = new SqlParameter("@id", SqlDbType.Int, 20);
        param[0] = new SqlParameter("@BookingName", System.Data.SqlDbType.VarChar, 50);
        param[1] = new SqlParameter("@BookedBy", System.Data.SqlDbType.VarChar, 50);
        param[2] = new SqlParameter("@ArrivalDate", System.Data.SqlDbType.SmallDateTime);
        param[0].Value = BookingName;
        param[1].Value = BookedBy;
        param[2].Value = ArrivalDate;
        for (int i = 0; i < param.Length; i++)
        {
            cmd.Parameters.Add(param[i]);
        }
        cmd.CommandType = System.Data.CommandType.Text;
        cmd.ExecuteNonQuery();
    }
    catch (System.Data.SqlClient.SqlException ex)
    {
        string msg = "Insert Error:";
        msg += ex.Message;
        throw new Exception(msg);
    }
    finally
    {
        conn.Close();
    }
}
protected void BtnCatering_Click(object sender, EventArgs e)
{
    if (Page.IsValid)
    {
        //call the method to execute insert to the database
        ExecuteInsert(BookingName.Text, BookedBy.Text);
        Response.Write("Record was successfully added!");
    }
}

在插入数据库之前将字符串转换为小日期时间

 if (ArrivalDate != DBNull.Value)
                param[2].Value = Convert.ToDateTime(ArrivalDate);
            else
            {
                param[2].Value = // default value
            }

您可以尝试使用日期时间而不是字符串。

param[2].Value = Convert.ToDateTime(ArrivalDate);

使用 DateTime.ParseExact 可以控制日期的确切转换:

CultureInfo provider = CultureInfo.InvariantCulture;
param[2].Value = DateTime.ParseExact(ArrivalDate, "MM/dd/yyyy hh:mm:ss tt", provider);