简体   繁体   English

将datetime2插入数据库

[英]Insert datetime2 into database

I am using datetime2 as the datatype for checkIn and checkOut . 我使用datetime2作为checkIncheckOut的数据类型。 Previously I can add into database with this code. 以前,我可以将此代码添加到数据库中。

//value for checkIn = 12/25/2015 2:00:00 PM
checkIn = DateTime.ParseExact(Session["checkInDate"].ToString(), "dd/MM/yyyy", CultureInfo.InvariantCulture).AddHours(14);

//value for checkOut = 12/26/2015 12:00:00 PM
checkOut = DateTime.ParseExact(Session["checkOutDate"].ToString(), "dd/MM/yyyy", CultureInfo.InvariantCulture).AddHours(12);

strInsert = "INSERT INTO Reservation ( checkInDate, checkOutDate) VALUES (@checkInDate, @checkOutDate)";

cmdInsert = new SqlCommand(strInsert, conn);
cmdInsert.Parameters.AddWithValue("@checkInDate", checkIn);
cmdInsert.Parameters.AddWithValue("@checkOutDate", checkOut);

But now it doesn't work and I am getting this error; 但是现在它不起作用了,我得到了这个错误。

"Conversion failed when converting date and/or time from character string". “从字符串转换日期和/或时间时转换失败”。

I think the error is caused by the check in value which contain the "PM" and "AM", but it is weird because previously I am able to add this into the database. 我认为该错误是由包含“ PM”和“ AM”的签入值引起的,但这很奇怪,因为以前我能够将其添加到数据库中。

Does anybody know how to fix this? 有人知道如何解决此问题吗?

It appears that you want to discard the time part of checkInDate . 看来您要舍弃checkInDate的时间部分。 Using ParseExact to do that is not really the correct way. 使用ParseExact这样做并不是正确的方法。 Instead you can use the .Date property of a DateTime and then add on the hours. 相反,您可以使用DateTime的.Date属性,然后添加小时数。

Also, to avoid the hassles which .AddWithValue can give, simply use .Add , so... 另外,为避免.AddWithValue可能带来的麻烦,只需使用.Add ,这样...

string s = "12/25/2015 2:00:00 PM";
DateTime checkIn = DateTime.Parse(s, CultureInfo.GetCultureInfo("en-US")).Date.AddHours(14);
// ....
string strInsert = "INSERT INTO Reservation (checkInDate, checkOutDate) VALUES (@checkInDate, @checkOutDate)";

using (SqlConnection conn = new SqlConnection(connStr))
{
    using (SqlCommand cmdInsert = new SqlCommand(strInsert, conn))
    {
        cmdInsert.Parameters.Add(new SqlParameter("@checkInDate", SqlDbType.DateTime2).Value = checkIn);
        // ....
    }
}

Note that you can store a DateTime in a Session value, there is no need to store it as a string. 请注意,您可以将DateTime存储在Session值中,而无需将其存储为字符串。

I notice that you quote the checkin date in USA date format (MM/dd/yyyy), but your format in .ParseExact is "dd/MM/yyyy". 我注意到您以美国日期格式(MM / dd / yyyy)引用签入日期,但是.ParseExact的格式为“ dd / MM / yyyy”。 This may also be a source of trouble. 这也可能是麻烦的根源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM