简体   繁体   English

通过参数添加(SqlDbType.DateTime)在 C# 中日期转换失败

[英]Date Conversion fails in C# via Parameter adding (SqlDbType.DateTime)

I am new to C#.我是 C# 新手。 I have this statement that fails:我有这个失败的声明:

dbCmd.Parameters.Add("@createdTime", SqlDbType.DateTime);

The value in the createdTime is: 1/18/2012 11:54:11 AM After a lot of troubleshooting I was able to narrow down the issue. createdTime 中的值是:1/18/2012 11:54:11 AM 经过大量故障排除后,我能够缩小问题范围。 It will work IF I change the value to: 2012-01-18 11:54:01 AM.如果我将值更改为:2012-01-18 11:54:01 AM,它将起作用。 So it doesn't work with the format.所以它不适用于格式。 I found the issue but how can I fix this issue?我发现了这个问题,但我该如何解决这个问题? I mean, the DateTime format is what it is.我的意思是,DateTime 格式就是这样。

Here is more of my code to explain:这是我要解释的更多代码:

        dbCmd.CommandType = CommandType.Text;
        dbCmd.CommandText = sqlCmd;
        
        dbCmd.Parameters.Add("@ID", SqlDbType.Int);
        dbCmd.Parameters.Add("@FullName", SqlDbType.NVarChar);
        dbCmd.Parameters.Add("@createdTime", SqlDbType.DateTime);

Parse the value explicitly in C# so the db parameter contains a DateTime, not a string:在 C# 中显式解析值,因此 db 参数包含 DateTime,而不是字符串:

dbCmd.Parameters.Add("@createdTime", SqlDbType.DateTime)
  .Value = DateTime.ParseExact(theVariableHoldingStringDateTime, "M/d/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);

If your use of Add there is just setting up a parameter that you're later giving a value to in a loop:如果您使用 Add 只是设置一个参数,您稍后会在循环中为其赋值:

for each line in text file parser blah blah

  dbCmd.Parameters["@createdTime"]
    .Value = DateTime.ParseExact(theVariableHoldingStringDateTime, "M/d/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);

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

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