5

Let's say I got this time 21:07:35 now and this time into a variable 21:02:37 like this

<?php
$current_time = "21:07:35";
$passed_time = "21:02:37";
?>

Now I want check if $current_time is less than 5 minutes then echo You are online So how can I do this in PHP?
Thanks
:)

4

4 回答 4

8

To compare a given time to the current time:

if (strtotime($given_time) >= time()+300) echo "You are online";

300 is the difference in seconds that you want to check. In this case, 5 minutes times 60 seconds.

If you want to compare two arbitrary times, use:

if (strtotime($timeA) >= strtotime($timeB)+300) echo "You are online";

Be aware: this will fail if the times are on different dates, such as 23:58 Friday and 00:03 Saturday, since you're only passing the time as a variable. You'd be better off storing and comparing the Unix timestamps to begin with.

于 2013-08-04T01:28:44.040 回答
3
$difference = strtotime( $current_time ) - strtotime( $passed_time );

Now $difference holds the difference in time in seconds, so just divide by 60 to get the difference in minutes.

于 2013-08-04T01:27:30.053 回答
2

Use Datetime class

//use new DateTime('now') for current
$current_time = new DateTime('2013-10-11 21:07:35');
$passed_time = new DateTime('2013-10-11 21:02:37');
$interval = $current_time->diff($passed_time);
$diff = $interval->format("%i%");

if($diff < 5){
 echo "online";
}
于 2013-08-04T01:31:48.970 回答
1
$my_time = "3:25:00";
$time_diff = strtotime(strftime("%F") . ' ' .$my_time) - time();


if($time_diff < 0)
    printf('Time exceeded by %d seconds', -$time_diff);
else
    printf('Another %d seconds to go', $time_diff);
于 2013-08-04T01:36:04.787 回答