0

I have some trouble comparing the fields to current time.

I have two fields in MySQL, who record the start time and end time of a lecture.

What I'm trying to do is check if the current time is during the start time and the end time.

$starttime and $endtime are in forms of DateTime.

The code's here:

$now = time();
$compare = mysql_query("SELECT * FROM lecture WHERE strtotime(starttime) < '$now' AND '$now' < strtotime(endtime)");

But it doesn't work.

I also tried this:

$now = new DateTime;
$compare = mysql_query("SELECT * FROM lecture WHERE starttime < '$now' AND '$now' < endtime");

But it broke too.

Could anyone tell me how to realize it? Many thanks.

6
  • what is the datatype of column starttime? can you give sample records? In mysql, you can use STR_TO_DATE to convert it to date (with time)
    – John Woo
    Dec 29, 2012 at 10:27
  • 2
    Please, don't use mysql_* functions in new code. They are no longer maintained and the deprecation process has begun, see the red box. Learn about prepared statements instead, and use PDO or MySQLi; this article will help you decide which. If you choose PDO, here is a good tutorial.
    – vascowhite
    Dec 29, 2012 at 10:27
  • @JW.: its format is DateTime, like this: 2012-12-29 08:32:00
    – Matt
    Dec 29, 2012 at 10:32
  • @vascowhite: Thank for the link and the details!
    – Matt
    Dec 29, 2012 at 10:33
  • @JW.: I've tried STR_TO_DATE(starttime) < '$now', but it doesn't work..
    – Matt
    Dec 29, 2012 at 10:37

2 Answers 2

7

use BETWEEN

SELECT * 
FROM   lecture 
WHERE  NOW() BETWEEN starttime AND endtime
0
1

$compare = mysql_query("SELECT * FROM lecture WHERE starttime < mysql_function AND mysql_function < endtime");

Replace mysql_function with one of the following function

1) SYSDATE(): example output as 2012-12-29 16:03:20

2) CURDATE(): example output as 2012-12-29

3) UNIX_TIMESTAMP(): example output as 1356777278

Depending upon 'startime and endtime' format replace one of the above function in the query.

2
  • Yes, it works great! Does CURDATE() stand for today's 00:00:00?
    – Matt
    Dec 29, 2012 at 10:59
  • @Matt: CURDATE() is for current date,what your thinking its correct.
    – Mahesh.D
    Dec 29, 2012 at 11:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.