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 开发者_如何学JAVAbetween 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
)
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;
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.
e.g
$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
精彩评论