简体   繁体   中英

Check if UK date is bewteen two dates in SQL

I need to check that a UK date, stored as string in the format dd/mm/yyyy in a database table ( postmeta.event_date ), is between two dates using SLQ format BETWEEN 'yyyy-mm-dd' AND 'yyyy-mm-dd+28' . I'm ok with working out the dates to check between, it's the date to check that I'm having issues with because it is in the wrong format for SQL.

I have no way of changing the format of the date to check, as it is attached to a post, and I don't know what posts to get out of the database until I can check if they are between my chosen dates...

Any ideas if this is possible, or am I looking at two queries (grab all the posts get the IDs of the ones that I actually want by checking the data in PHP)? Thanks.

The way to convert your date would be to use str_to_date :

STR_TO_DATE(event_date, '%d/%m/%Y')

This converts your date to something you can use in your BETWEEN formula.

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

You can use the following construction:

STR_TO_DATE(postmeta.event_date, '%d/%m/%Y') BETWEEN 'yyyy-mm-dd' AND 'yyyy-mm-dd' + INTERVAL 28 DAY

However using a custom date format, such that is not supported natively by the database, in a column that can used for filtering is commonly a bad design, unless maybe one knows exactly what they are doing.

A query relying on the filter provided above will work, but it won't be very efficient as such range lookup cannot be optimized through indexes.

How about

WHERE event_date BETWEEN 'yyyy-mm-dd' AND DATE_ADD('yyyy-mm-dd', INTERVAL 28 DAY)

Obviously the yyyy-mm-dd will be replaced with actual values:

WHERE event_date BETWEEN '2011-05-11' AND DATE_ADD('2011-05-11', INTERVAL 28 DAY)

If your date string is not in the expected format, you'll have to parse it first. You can do that in PHP or use STR_TO_DATE .

WHERE event_date 
BETWEEN 
    STR_TO_DATE('01/05/2011','%d/%m/%Y') AND
    DATE_ADD(STR_TO_DATE('01/05/2011','%d/%m/%Y'), INTERVAL 28 DAY)

Here is period from today - to the next 28 days

  $now = mktime();
  //set your period date
  $from = mktime(0, 0, 0, date("m",$now), date("d",$now), date("Y",$now));
  $to   = mktime(23, 59, 59, date("m",$now), date("d",$now)+28, date("Y",$now));

HERE IS YOUR QUERY

 SELECT * FROM `postmeta` WHERE UNIX_TIMESTAMP(`event_date`)>='".$from."' AND UNIX_TIMESTAMP(`event_date`)<='".$to."'

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