0

SQL statement:

SELECT * FROM table 
WHERE eventdate >= DATE(NOW()) 
AND eventtime > TIME(NOW()) 
ORDER BY eventdate ASC, eventtime ASC;

The goal is to select the event that is coming up next. It works just fine so long as there are not two events on the same date. For example:

Event 1, 11/17/2016 7:00am
Event 2, 11/17/2016 2:00pm
Event 3, 11/18/2016 9:00am

I want to select event 2 since it is passed 7:00 am on the 17th. The statement above would still select event 1.

Brian Breeden
  • 91
  • 1
  • 3
  • 8

3 Answers3

1

This should work:

SELECT * FROM table 
WHERE eventdate > DATE(NOW())
OR
    (eventdate = DATE(NOW()) AND eventtime > TIME(NOW()) )

ORDER BY eventdate ASC, eventtime ASC;

Basically you compare if date is in the future(tomorrow) or date is today and time is passed.

If your date is in the future you don't care about the time in this case.

Try it.

  • Looks like the problem is that the NOW() is two hours behind. Any idea on how to change the time to EST? – Brian Breeden Nov 17 '16 at 13:59
  • Here is the answer: http://stackoverflow.com/questions/13916747/set-mysql-database-timezone-to-gmt –  Nov 17 '16 at 14:01
0

I would need the value stored in eventdate and eventtime fields in your table in context to your example. because if you are checking time > TIME(NOW()), it should not pick this event if time is passed.

  • I see the first time is set at 8:06 when the event is at 7:00 am. If the code is running between 7:00 and 8:06, it will take the first event of the day as well. The timezone doesn't seems to be an issue as SQL statement is using NOW() function which is the function executed at the server time. It all depends what actually is the exact time at the server and if there is any time difference between place of event and server's time. – Manish Sharma Nov 17 '16 at 14:36
0

As determined in the comments, the issue lies with the timezone currently used by the server where the database resides. Because of this, and that you are using PHPmyAdmin, I believe you do not have the authority to change the server timezone.

Your possible solutions are:

  • Use data that is already in MST (UTC-07) or whatever time zone the server is on
  • Use the current data and subtract 2 hours or convert the data to a time zone
  • Rewrite the query to use NOW() + 2 hours
Community
  • 1
  • 1
Fritz
  • 624
  • 1
  • 7
  • 14
  • Suggest you remove the "Change (or find who can change) the server timezone". That would just move the problem to some other user which is not in the same time zone.. Btw, this is why in most cases it makes sense to store UTC date/time in the database, not local date/time. Everyone agrees on the current UTC time... – user1429080 Nov 17 '16 at 15:23
  • Noted and updated. I was answering under the impression that this was a personal project when I shouldn't have made that assumption. – Fritz Nov 17 '16 at 15:35