开发者

Override DateTime.MinValue

开发者 https://www.devze.com 2022-12-21 23:30 出处:网络
I am using Dat开发者_如何学编程etime.Minvalue which return 1.1.0001. This value can not be stored to DB because year is smaller than 1975.

I am using Dat开发者_如何学编程etime.Minvalue which return 1.1.0001. This value can not be stored to DB because year is smaller than 1975.

Is it possible to override DateTime.Minvalue to 1.1.1901?

Regards


No, it's not. You could instead use SqlDateTime.MinValue (1753-01-01), define your own constant for 1901-01-01 if that's what you want to use, or actually use a nullable DateTime:

DateTime? dateVal = null;

In the instance where no date is specified, a null may make more sense and persist DBNull.Value to the database instead of a "special" value like you're currently doing.

Or, as a final option....at the point you come to persist to the database, do a check for DateTime.MinValue and switch in an alternative. But I'd recommend the nullable DateTime.


It is possible. Everybody who finds this code will hate you. Some will likely harm you.

typeof(DateTime)
    .GetField ("MinValue")
    .SetValue (typeof(DateTime), new DateTime(1901, 1, 1));


what about using a method for this

DateTime GetMinDateTime()
{
   return DateTime.MinValue.AddYears(900);
}


You should use nullable DateTime for such a thing.


No, it's a static field, and those can't be overridden.

You will need to write a Guard or conversion of some sort


No. Since DateTime.MinValue is a static, there is no simple means to override. I would suggest replacing DateTime.MinValue with a constant, or in your data access code, convert DateTime values equal to DateTime.MinValue to 1900-01-01.


If you're only coding for Microsoft SQL Server you can substitue System.DateTime for System.Data.SqlTypes.SqlDateTime. If I have understood correctly, the System.Data.SqlTypes data types are directly compatible with the database data types, which avoids the situation you encountered.

0

精彩评论

暂无评论...
验证码 换一张
取 消