How to check if a date is between date1 and date2 using mysql?

二次信任 提交于 2019-11-30 15:37:18

问题


I'm trying to write a query that will check today's date against my table columns date1 and date2 in mysql/php.. This is what I'm after:

'events' table:

  • date1 = start date (XXXX-XX-XX)
  • date2 = end date (XXXX-XX-XX)

query:

  • select * from events where 2012-01-18 between date1 and date2 (or equal to date1 and date2)

But I'm not sure how to go about it.. any help would be appreciated :)

EDIT:

Maybe I was unclear.. if todays date = '2012-01-18' I need it to find results if today's date is between the date range of date1 and date2.. So date1 may be '2012-01-04' and date2 may be '2012-01-21'.. so if todays date falls between or on those dates, a result is returned..


回答1:


SELECT * FROM events 
  WHERE date1<='2012-01-18'
  AND date2>='2012-01-18'



回答2:


If your referring to compare the date today is between a start and end date, I think you should use this:

SELECT *
FROM table
WHERE '2014-08-20' >= start_date
AND '2014-08-20' <= end_date

Hope this helps :)




回答3:


SELECT *
FROM events
WHERE date1 <= '2012-01-18'
AND date2 >= '2012-01-18';

This should get you started. You can use DATE(NOW()) to get today's date if you don't want to hardcode a date.




回答4:


Try this,

SELECT * FROM events  
  WHERE date1<='2012-01-19'  
  AND date2>='2012-01-18'  



回答5:


Though there are many answers available to this question I would like to give my response regarding the same situation I faced.

I am using php to query mysql database.

first what I do is to convert the date in the mysql supported date format which is yyyy-mm-dd

$date = new DateTime($date);
$date=date_format($date, 'Y-m-d');

in the query's where clause I use BETWEEN

"'$date' BETWEEN start_date AND end_date"

this works perfectly given the case described here.




回答6:


Modified version of styfle's code

$date1 = '2010-01-01'; // example min
$date2 = '2015-01-01'; // example max
$sql = "SELECT * FROM events WHERE $date1 >= '2012-01-18' AND $date2 <= '2012-01-18';";
$result = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($result) != 0) {
    // This date is equal to or within the range specified
} else {
    // The date was not within the range specified
}

then you can have code executed based on the result



来源:https://stackoverflow.com/questions/8904597/how-to-check-if-a-date-is-between-date1-and-date2-using-mysql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!