验证日期是否在 SqlDbType.DateTime 范围内

发布于 2024-09-30 04:14:52 字数 536 浏览 0 评论 0原文

我想在将 System.DateTime 值作为参数添加到 SqlCommand 实例之前验证它。

SqlDbType 枚举的 MSDN 文档表示:

日期和时间数据的值范围为 1753 年 1 月 1 日到 9999 年 12 月 31 日,精确度为 3.33 毫秒。

为了验证该值,我使用

public readonly DateTime SqlDateTimeMin = new DateTime(1753, 1, 1);
public readonly DateTime SqlDateTimeMax = new DateTime(9999, 12, 31);

if (value < SqlDateTimeMin || value > SqlDateTimeMax)
    // Validation check fails
else
    // Validation check succeeds

Is这是最好的方法吗?除了对这些最小值和最大值进行硬编码之外,还有其他选择吗?

I want to validate a System.DateTime value before I add it as a parameter to my SqlCommand instance.

The MSDN documentation for the SqlDbType enumeration says:

Date and time data ranging in value from January 1, 1753 to December 31, 9999 to an accuracy of 3.33 milliseconds.

To validate the value, I'm using

public readonly DateTime SqlDateTimeMin = new DateTime(1753, 1, 1);
public readonly DateTime SqlDateTimeMax = new DateTime(9999, 12, 31);

if (value < SqlDateTimeMin || value > SqlDateTimeMax)
    // Validation check fails
else
    // Validation check succeeds

Is this the best way? Is there an alternative to hard coding these min and max values?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

不可一世的女人 2024-10-07 04:14:52

SqlDateTime.MinValueSqlDateTime.MaxValue

注意:这些是 SQL 类型 min/max,而不是像前 2 个答案那样的 .net 类型:-)

What about SqlDateTime.MinValue and SqlDateTime.MaxValue?

Note: these are SQL type min/max not the .net types like the previous 2 answers :-)

↘紸啶 2024-10-07 04:14:52
SqlDateTime.MaxValue = 12/31/9999
SqlDateTime.MinValue = 1/1/1753

然后您的代码将显示:

if (value < SqlDateTime.MinValue || value > SqlDateTime.MaxValue)

我认为这比 DateTime.MaxValueDateTime.MinValue 更能满足您的需求,因为 DateTime.MinValue 不是 1 /1/1753 而是 1/1/0001。

SqlDateTime.MaxValue = 12/31/9999
SqlDateTime.MinValue = 1/1/1753

Your code would then read:

if (value < SqlDateTime.MinValue || value > SqlDateTime.MaxValue)

I think this meets your needs better than DateTime.MaxValue and DateTime.MinValue, because DateTime.MinValue is not 1/1/1753 but rather is 1/1/0001.

甲如呢乙后呢 2024-10-07 04:14:52

我认为真正的问题是为什么您的用户输入的日期超出了这个范围?您验证它的代码没问题,但我建议这是用户界面中的一个更大问题,人们可以输入虚假日期。

I think the real question is why is your users entering dates outside of this range? Your code to validate it is fine, however I'd suggest it's a larger problem in the UI where people can enter bogus dates.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文