简体   繁体   中英

String date comparison C#

I have an application that pulls a date from a MySQL database (string format: 01-jan-2000). I need to compare this data with the date entered in a TextBox.

This is what i have so far:

String query = "select * from tb_demographic_data where date_of_birth LIKE '%" +
       txb_startDate.Text + "' OR (str_to_date(date_of_birth,'%d,%b,%Y') <= 
       str_to_date('"+txb_startDate.Text+"','%d,%b,%Y'))

When I run the query I get no results. Nothing is wrong with my sql code. I think the error occurs when i change the string to a date with str_to_date() . Can anyone help?

Don't do string comparisons of dates. Change the column in the database to be a date, and update your query to accept a date value using a parametrized statement or similar.

It looks like your date format is wrong... '%d,%b,%Y' is saying that the separators are commas. I would imagine you want something like '%d-%b-%Y' .

As Nikhil pointed out, having a user enter a date in a date/calendar/clock control is typically a much better choice. In addition, I would highly recommend not taking user input from a textbox and simply pasting it inside a SQL string. This leads to SQL injection .

I would recommend that you either use one of the above recommended controls to have users specify a specific DateTime , or convert the data in your text box to a DateTime object . Assuming you are using DbCommand objects to run your query, you can then use a parameterized query and pass in your DateTime as a parameter, rather than directly putting it into the command. Your SQL could look like the following:

select * from tb_demographic_data
where date_of_birth <= @startDate

You would then have to add a DbParameter to your DbCommand with a ParameterName of "@startDate" and a Value of your DateTime object.

i figured it out. I'm sure its not the most efficient way to do this but I'm fairly new to this. Here it is: I just parsed the two strings as dates and calculated the date difference between them. If the answer is positive then the first date comes before the second and vice versa

select * from tb_demographic_data 
where date_of_birth 
    LIKE '%" + txb_startDate.Text + "' 
    OR (datediff(str_to_date('" + txb_startDate.Text + "', 
                             '%d-%b-%Y'), 
                 str_to_date(date_of_birth,
                             '%d-%b-%Y'))>=0) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM