Share via


Convert SQL DateTime field to C# DateTime

Question

Monday, November 24, 2008 10:40 AM | 1 vote

Hello,
 
I have run into a seemingly simple problem, but I cannot get it to work. I have an SQL Server Express 2008 database with a datetime column. I am simply trying to cast this into a C# DateTime data type, but to no avail.

I thought this would suffice:

DateTime date = Convert.ToDateTime(resultSet["myDateColumn"].ToString());

However, date is assigned the value 1/1/1 (MinValue). If I try to output resultSet["myDateColumn"].ToString(), the correct date is displayed so there is no problem with the database or SQL query.

All replies (2)

Monday, November 24, 2008 4:22 PM âś…Answered | 1 vote

Just cast it to DateTime.  If it's nullable, cast it to Nullable<DateTime>, which can also be written as "DateTime?".

DateTime? value = (DateTime?)resultSet["myDateColumn"];

That should do it for you.

You won't be able to set DateTime.Minimum into the SQL database.  SQL won't take 1/1/1 as a date, because it's earliest date is much later. Try using SqlDateTime.MinValue instead. David Morton - http://blog.davemorton.net/


Monday, November 24, 2008 4:30 PM | 1 vote

David M Morton said:

Just cast it to DateTime.  If it's nullable, cast it to Nullable<DateTime>, which can also be written as "DateTime?".

DateTime? value = (DateTime?)resultSet["myDateColumn"];

That should do it for you.

You won't be able to set DateTime.Minimum into the SQL database.  SQL won't take 1/1/1 as a date, because it's earliest date is much later. Try using SqlDateTime.MinValue instead.


David Morton - http://blog.davemorton.net/

Thanks David,
I'll have a project where I might be able put that idea to use.  The VS Designers dont't seem to be smart enough to deal with the SQL TimeStamp data type.Mark the best replies as answers. "Fooling computers since 1971."