开发者

How to convert sqldatetime.minvalue to datetime?

I can't seem to convert a sqldatatime.minvalue to a datetime object.

I tried:

Datetime dt = Convert.ToD开发者_开发百科ateTime(SqlDateTime.MinValue);

That obviously didn't work.


No need to convert. SqlDateTime has a Value property that returns a DateTime.

DateTime dt = SqlDateTime.MinValue.Value;


Any reason not to just use the explicit conversion operator?

DateTime dt = (DateTime) SqlDateTime.MinValue;

That works for me:

using System;
using System.Data.SqlTypes;

class Test
{
    static void Main()
    {
        DateTime dt = (DateTime) SqlDateTime.MinValue;
        Console.WriteLine(dt);
    }
}


The answers you have received have shown you two different ways to convert the value. One is to use an explicit conversion defined for SqlDateTime to DateTime, the other is to access the .Value property on the SqlDateTime instance, which returns a DateTime.

var date = theSqlDate.Value; // via property
var date = (DateTime)theSqlDate; // via explicit conversion

There are tradeoffs that are worth considering. SqlDateTime supports the concept of null values in the database (DBNull, referenced by another now-deleted answer) through the value SqlDateTime.Null. If you access the Value property on a "null" instance, you will run into a SqlNullValueException. On the other hand, an explicit conversion to DateTime results in {January 1, 1900 12:00:00 AM}. Neither of these results may be desired in your code. Overwriting a valid null entry at the database with a non-null default value might be just as bad as getting an exception at runtime.

If you have a nullable column in the database, and if you are working with SqlDateTime, you may need to explicitly test for and treat SqlDateTime.Null differently, and then it might not matter which approach you take for converting other values.

DateTime? date;
if (theSqlDate.Equals(SqlDateTime.Null))
    date = null
else 
    date = theSqlDate.Value; // or (DateTime)theSqlDate;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜