The problem mentioned below has been solved and code has been changed to reflect changes.
I want to check the current date against a date stored in my MySQL database. to retrieve the current date I am using the nist time server which returns a date in the format MM-DD-YYYY and in my database I have values stored in the format “YYYY-MM-DD.” What I want to do is checking if the date I pass is equal to the date in the database, then do something.
The code I am using is the following one:
// The code originally posted has been changed to reflect changes made and it is now working fine (problem solved) a big thank you to all those who replied.
DateTime currentDate = InternetTime();
//DD/MM/YYYY is returned here convert to YYYY/MM/DD
string currentDate = x.ToString("yyyy-MM-dd");
con = new MySqlConnection(conString);
MySqlDataAdapter da = new MySqlDataAdapter();
MySqlCommand cmd = new MySqlCommand("SELECT id AS oDates FROM open_dates WHERE dates=?currentDate",con);
cmd.Parameters.AddWithValue("?currentDate",currentDate);
da.SelectCommand = cmd;
DataTable dt = new DataTable("openDates");
da.Fill(dt);
the “dt” table remains empty because TryParseExact doesn’t write anything to dateValue and so it remains “01-01-0001” or something like that. Where am I going wrong? It would be great if anyone could help me.
There is actually a workaround that I thought of; I could store strings in the database right away, and then check them, but that would be cheating; I want the date to work.
I tried searching for MySQL commands that could help me, but I couldn’t find any.
You’re ignoring the result of
DateTime.TryParseExact. It will almost certainly be returningfalse, indicating that it’s failed to parse the string – and it’s documented to writeDateTime.MinValueinto the out parameter in that case. You should definitely be checking the return value and acting accordingly if parsing is failing.I suspect you want a format string of “yyyy-MM-dd” by the way.
Note that you shouldn’t be including the date in your SQL string directly in the following line – you should use a parameterized query instead.
Indeed, you shouldn’t be converting
xto a string either – it’s already aDateTime, so why are you converting it to a string and then parsing it? Your comment indicates that you think aDateTimevalue has a particular format – it doesn’t, any more than numbers do – formats relate to how a value is converted into text, and isn’t inherent in the value itself.