gpt4 book ai didi

asp.net - 错误 - SqlDateTime 溢出。必须介于 1/1/1753 12 :00:00 AM and 12/31/9999 11:59:59 PM 之间

转载 作者:行者123 更新时间:2023-12-03 05:23:27 24 4
gpt4 key购买 nike

我一直在使用我编写的这段代码,它以最不清楚的方式工作。我希望在数据库中插入一行,其中包含两列日期时间:

myrow.ApprovalDate = DateTime.Now
myrow.ProposedDate = DateTime.Now

然而,当我更新数据库时,我收到此错误:

SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.

我什至尝试从数据库复制插入的值并将其硬编码到正在更新的对象中:

// I copied this value from the DB
myrow.ApprovalDate = Convert.ToDateTime("2008-12-24 00:00:00.000");

仍然是同样的错误,奇怪的是上面的技巧对于第一次插入数据库有效,但从那时起就失败了。知道发生了什么吗?

最佳答案

一个DateTime在 C# 中是值类型,而不是引用类型,因此不能为 null。但它可以是常数 DateTime.MinValue超出了 Sql Server 的范围 DATETIME数据类型。

保证值类型始终具有(默认)值(零),而无需始终需要显式设置(在本例中为 DateTime.MinValue)。

结论是您可能有一个未设置的 DateTime 值,您正在尝试将其传递到数据库。

DateTime.MinValue = 1/1/0001 12:00:00 AM
DateTime.MaxValue = 23:59:59.9999999, December 31, 9999,
exactly one 100-nanosecond tick
before 00:00:00, January 1, 10000

MSDN:DateTime.MinValue

<小时/>

关于Sql Server

datetime
Date and time data from January 1, 1753 through December 31, 9999, to an accuracy of one three-hundredth of a second (equivalent to 3.33 milliseconds or 0.00333 seconds). Values are rounded to increments of .000, .003, or .007 seconds

smalldatetime
Date and time data from January 1, 1900, through June 6, 2079, with accuracy to the minute. smalldatetime values with 29.998 seconds or lower are rounded down to the nearest minute; values with 29.999 seconds or higher are rounded up to the nearest minute.

MSDN:Sql Server DateTime and SmallDateTime

<小时/>

最后,如果您发现自己通过了 C# DateTime作为 sql 的字符串,您需要将其格式化如下以保留最大精度并防止 sql server 抛出类似的错误。

string sqlTimeAsString = myDateTime.ToString("yyyy-MM-ddTHH:mm:ss.fff");
<小时/>

更新(8年后)

考虑使用sql DateTime2与 .net 更好地保持一致的数据类型 DateTime日期范围 0001-01-01 through 9999-12-31和时间范围 00:00:00 through 23:59:59.9999999

string dateTime2String = myDateTime.ToString("yyyy-MM-ddTHH:mm:ss.fffffff");

MSDN datetime2 (Transact-SQL)

关于asp.net - 错误 - SqlDateTime 溢出。必须介于 1/1/1753 12 :00:00 AM and 12/31/9999 11:59:59 PM 之间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/468045/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com