简体   繁体   中英

Selecting entries by date - >= NOW(), MySQL

I have a Calendar of Events table and I would like to select events with dates equal to or greater than today. When I use the following SELECT statement, it only retrieves events in the future (> NOW()):

<?php    
$db->query("SELECT * FROM events WHERE event_date >= NOW()");
?>

How would I go about selecting all events that are either today or in the future?

Thank you

You are looking for CURDATE() :

$db->query("SELECT * FROM events WHERE event_date >= CURDATE()");

Or:

$db->query("SELECT * FROM events WHERE event_date >= CURRENT_DATE()");

The reason that this query:

SELECT * FROM events WHERE event_date >= NOW()

...returns records from the future, is because NOW() includes the time as well as the date. And that time portion indicates the time at which the [function or triggering] statement began to execute. So that means the start of the day in a DATETIME data type looks like: 2010-06-24 00:00:00 (YYYY-MM-DD HH:MM:SS, to microsecond precision), which NOW() would show something like 2010-06-24 14:24:31 ...

Here are your options:

SELECT * FROM events WHERE event_date >= DATE(NOW())
SELECT * FROM events WHERE event_date >= DATE(CURRENT_TIMESTAMP)
SELECT * FROM events WHERE event_date >= CURRENT_DATE()
SELECT * FROM events WHERE event_date >= CURRDATE()

You could also do

<?php    
$db->query("SELECT * FROM events WHERE UNIX_TIMESTAMP(event_date) >=     UNIX_TIMESTAMP(NOW())");
?>

Which is more accurate than using CURTIME() if by any chance your using time as well as date

If you care only about the date, not the time, use CURDATE() instead of NOW() .

Of course you can alternatively use the synonym CURRENT_DATE (with or without parentheses after it), but the docs I pointed to give CURDATE as the first spelling;-).

Your issue is that now() is very accurate. So dates for today and before now because they started at the beginning of the day.

Use this:

select * from events where datediff(event_date, now()) >= 0;

Here's the difference between CURDATE and NOW:

mysql> select CURDATE();
+------------+
| CURDATE()  |
+------------+
| 2017-03-17 |
+------------+
1 row in set (0.03 sec)

mysql> select NOW();
+---------------------+
| NOW()               |
+---------------------+
| 2017-03-17 09:04:45 |
+---------------------+
1 row in set (0.00 sec)

I always use NOW just to be accurate

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