1

Im building a bus schedule app.

In the mysql db I have a 'time' field that is static - let's say 15:23 which is the scheduled time for the bus and never changes from one day to the next - the bus always comes at 15:23. It's 3:20 PM and the user is running for the bus stop. How do I present the user with "The next bus is in 3 minutes"

Thanks in advance! Chris

3
  • What's the type of the 'time' field? Are you wondering about the whole query, or just how to compare times?
    – outis
    Nov 1, 2009 at 18:47
  • Oh yeah, Im working in php - sorry Nov 1, 2009 at 18:49
  • I can do the query, just can seem to compare the times from the query result and now. And the type is "time". Nov 1, 2009 at 18:51

3 Answers 3

2

You can also do it in PHP:

// set this to the appropriate time zone if mktime gives a warning
date_default_timezone_set("America/Los_Angeles");

$bus = mktime(11, 0); // hour : minute; other fields default to now
$now = time();
echo (($bus - $now) / 60) . " minutes to go\n";

If you're getting the time from MySQL instead of time(), use MySQL's UNIX_TIMESTAMP() function.

0

be careful when your calculation goes over midnight, for example if it's 23:20 and the bus comes at 0:05, a simple subtraction won't work. Always make sure scheduled time is later than current time, e.g.

$now = time();
$sched = "00:43";

$sched_time = strtotime($sched);
if($sched_time < $now)
     $sched_time = strtotime("tomorrow $sched");

$diff =  $sched_time - $now;
echo "$diff seconds to go";
0

In MySQL you can use the TIMEDIFF function and the CURTIME function to do this:

TIMEDIFF(bus_time, CURTIME())

Your Answer

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

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