I have a problem of reading a dateTime column from a database. I set a parameter which is a datetime, but it does not read it. I am wondering what could be wrong.

This is how I have written a date and time in the database:

And this is my code with the parameter. In the value "Datum" you can see I got the same date and time as it is in the database. But the reader (bralec) does not read it.

http://file.si/files/2081_glnve/C%23_datetime_Lista2.JPG

What could be wrong?

Dani AI

Generated

Quick checklist and concrete fixes for 's "DateTime issue" (expanded from 's note about regional settings).

Common causes (quick):

  • The query returns no rows (so the reader never gets a DateTime).
  • The selected column is NULL or contains a MySQL "zero" date (0000-00-00 00:00:00).
  • Parameter name/type mismatch (parameter name in SQL does not match the parameter added, or a string is sent instead of a typed DateTime).
  • Connector/NET conversion rules for zero dates or type conversion errors.

Practical steps to diagnose and fix:

  • Confirm the command actually returns rows (check reader.Read() / reader.HasRows). If no rows, log the final SQL + parameter values.
  • If a column can be NULL, always check IsDBNull before calling GetDateTime.
  • Prefer typed parameters. Add the parameter as a DateTime type instead of formatting a string (this avoids regional-format issues that mentioned).
  • If the database contains zero dates, enable the Connector/NET options Allow Zero Datetime and (optionally) Convert Zero Datetime in the connection string so the driver will handle 0000-00-00 00:00:00 values without throwing.

Helpful references:

Minimal examples (safe patterns):

cmd.Parameters.Add("@Datum", MySqlDbType.DateTime).Value = someDateTimeValue;
int idx = reader.GetOrdinal("Datum");
DateTime datum = reader.IsDBNull(idx) ? DateTime.MinValue : reader.GetDateTime(idx);

If these checks still fail, confirm exact SQL being executed and the parameter names/values (log them). That usually reveals whether the problem is a missing row, a NULL/zero date, or a parameter mismatch.

Do not customize the regional settings (i.e. date,time).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.