Search code examples
c#datetimesqldatetime

SqlDateTime overflow, but I want a NULL or MinValue


On this project, I am tracking when something is created, edited, and finally processed. I have three DateTime fields setup for this. The code below is for when I create the record.

newsArchive.CreateDateTime = DateTime.Now;
newsArchive.ModifyDateTime = DateTime.MinValue;
newsArchive.SendDateTime = DateTime.MinValue;
naRepository.Add(newsArchive);
naRepository.Save();

I am getting "SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM." when I try to add it. I know I can't send a NULL. How would you handle this?

I am using Linq2SQL to process this.


Solution

  • Why can't you send a null? AFAIK, Linq2SQL supports nullable value types; you just need the column in the DB to be nullable or L2S won't project the DAO with the nullable type.

    You could use (DateTime)(SqlDateTime.MinValue) instead of DateTime.MinValue. This will use the minimum SQL-compatible datetime value, explicitly cast to DateTime.

    Though both SqlDateTime and DateTime actually store time as a UInt64 "Ticks" value, the difference between the two types is that SQL Server uses a different epoch (value for zero) and a different resolution (what 1 "tick" represents in fractions of a second) than the CLR's DateTime.