简体   繁体   中英

Comparing String Dates Pulled From MySql Database

I have a relation in a MySQL database which stores dates in the form of varchar along with other attributes. It looks something like:

Answers answerId answer questionId date

I have a web application where the user will select a 'from' and 'to' date and I will need to pull the relevant answers between the ranges provided. So my question is how would I implement a php file which queried the database correctly pulling out the answers between the dates provided..

If you date is in YY-mm-dd (From greatest to lowest, with leading zeros) you can compare it as string(lexicographically)

But You should use proper datatype for date ( DATE , DATETIME , TIMESTAMP )

Here is a simple solution for it:

You can convert a date (that is already stored in your MySQL db) to Unix time and compare it like any number.

eg

$date1 =  strtotime("2010-11-12");  
$date2 =  strtotime("2010-11-14");  

and just compare $date1 and $date2 .

here is the link that will help you http://php.net/manual/en/function.strtotime.php

As @RiaD wrote you use proper date types. But if you can't change type you should convert Varchar string to DATETIME using STR_TO_DATE .

See http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_str-to-date

So you query will be looked like

Select * from table
where STR_TO_DATE(field_name, 'YOUR_DATE_FORMAT') between start_date and end_date;

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