Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a datetime value from a SQL database

Tags:

c#

sql

datetime

How can I read datetime fields from a SQL database?

This is not working:

emp.DateFacturation = (DateTime)(dr["DateFacturation"])

nor is this:

emp.DateFacturation = DateTime.Parse(dr["DateFacturation"].toString());
like image 520
Med Amine Avatar asked Oct 31 '12 13:10

Med Amine


People also ask

Can we extract date from timestamp in SQL?

In MySQL, use the DATE() function to retrieve the date from a datetime or timestamp value. This function takes only one argument – either an expression which returns a date/datetime/ timestamp value or the name of a timestamp/datetime column.


1 Answers

Since you've commented a now deleted answer with:

dr is a DataReader

You can use SqlDataReader.GetDateTime. You should check first if the value is DBNull with DataReader.IsDBNull:

DateTime dateFacturation;
int colIndex = dr.GetOrdinal("DateFacturation");
if(!dr.IsDBNull( colIndex ))
    dateFacturation = dr.GetDateTime( colIndex );

I use GetOrdinal to get the column index of the column name to pass it to GetDateTime.

like image 61
Tim Schmelter Avatar answered Sep 28 '22 04:09

Tim Schmelter