C# DateTime.MinValue is not the same as SqlDateTime.MinValue

ASP.Net, SQL Add comments

kick it on DotNetKicks.com

Working with non-nullable types in C# can be a bit of a pain. For instance when I have a date as a string and need to parse it into a DateTime what should the value be if the parse fails? I can’t use null because DateTime is not a nullable type.

This is exactly the dilema I encountered today. No worries, I’ll use DateTime.MinValue that way it is constant and I don’t have to worry about being consistent if I had chosen an arbitrary value of my own.

Well as it turns out I did have some worries. Sql Server 2000’s minimum DateTime value is not the same, in fact it is quite different. This kept causing errors.

For your reference here are some values you should take note of.

DateTime myDate = DateTime.MinValue; //=> 1/1/0001
SqlDateTime mySqlDate = SqlDateTime.MinValue; //=> 1/1/1753
//also note that SQL Server's smalldatetime min value is 1/1/1900

So my problem was easily averted, after a quick Google search. I just had to use SqlDateTime.MinValue instead of DateTime.MinValue.

Cheers

If you liked this article consider subscribing to my free rss article feed to automatically get new articles in your feed reader.

3 Responses to “C# DateTime.MinValue is not the same as SqlDateTime.MinValue”

  1. Nick Berardi Says:

    Why don’t you use a nullable date time?

    DateTime? whateverDate = null;

    The question mark makes the datetime nullable, it actually works for any struct type even Enums.

  2. Justin Says:

    Had I known that little gem I probably would have :D. I just switched from .Net 1.1 about 6 months ago so I don’t know all the newest features yet.

  3. Nick Berardi Says:

    yeah this has been a savior many times for me.

Leave a Reply

WP Theme & Icons by N.Design Studio
Entries RSS Login