Skip to content
Advertisement

Microsoft SQL Server database / Visual Studio C# : date handling

I’m trying to figure out what would be the quickest and most convenient way to grab dates from the database and parse/cast them correctly into my DAL (DataAccessLayer) methods.

The columns inside my database are of datatype date.

Specifically I have this Order class:

And then of course I have a DAL method for, let’s say, getting a list of orders from the database.

NOTE: On my web I will only need YEAR, MONTH and DAY from the above mentioned dates. Not sure if that helps you, probably not but just wanted to say.

Advertisement

Answer

A date column in sql maps to a DateTime in c#. There is no need to do any special parsing. Assuming you’re using a SqlDataReader, just use SqlDataReader.GetDateTime, or if you don’t know the column ordinal use the indexer and pass it the column name then cast the result to a DateTime just like you’re doing with the "id" column.

If the date columns in the database are nullable, then you need to account for that in your code by making the DateTime objects nullable (DateTime?) and checking for null when reading the results from the SqlDataReader.

You could put this into an extension method on SqlDataReader if you wanted…

If your view only needs to display the year, month, and day then you can do that in several ways. For example, DateTime.ToShortDateString or DateTime.ToString(string).

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement