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());
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With