How to convert sqldatetime.minvalue to datetime?

C#Datetime

C# Problem Overview


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

I tried:

Datetime dt = Convert.ToDateTime(SqlDateTime.MinValue);

That obviously didn't work.

C# Solutions


Solution 1 - C#

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

DateTime dt = SqlDateTime.MinValue.Value;

Solution 2 - C#

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);
    }
}

Solution 3 - C#

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;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncodecompletingView Question on Stackoverflow
Solution 1 - C#Jeff OgataView Answer on Stackoverflow
Solution 2 - C#Jon SkeetView Answer on Stackoverflow
Solution 3 - C#Anthony PegramView Answer on Stackoverflow