Insert datetime in SQL without millisecond using a parameter

前端 未结 1 1135
滥情空心
滥情空心 2021-01-26 16:55

I need to insert a .net DateTime in my SQL Server DataBase without the milliseconds.

dtNow = Date.Now
myCmd.Parameters.AddWithValue(\"MyDate\", dtNow)

相关标签:
1条回答
  • 2021-01-26 17:10

    While you could subtract the number of milliseconds as suggested in comments, that would still leave you with submillisecond values. That may not cause a problem, but it's possible that the driver will round the submillisecond value up to a whole millisecond. It's cleaner (IMO) to avoid having any subsecond value at all, so that the value you insert is the same as the value which gets stored. I'd prefer to use:

    var truncated = new DateTime(dtNow.Year, dtNow.Month, dtNow.Day,
                                 dtNow.Hour, dtNow.Minute, dtNow.Second);
    // Use truncated as the parameter in your command
    

    That way it will clearly only have year/month/day/hour/minute/second values.

    If you find yourself doing this regularly, you might want to write an extension method so that you can use:

    var truncated = dtNow.TruncateToSecond();
    
    0 讨论(0)
提交回复
热议问题