views:

100

answers:

3

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

A: 

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

TIMEDIFF(bus_time, CURTIME())
+2  A: 

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.

alltom
A: 

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";
stereofrog