2014-01-09 138 views
0

我目前正在开发一个PHP程序,它将显示一个主题的按钮。但我不知道算法是否在计划开始前15分钟。在PHP中比较时间

例如。该主题将于下午2:30开始。系统将比较当前时间,如果当前时间是下午2:15(主体开始前15分钟),则会显示可点击按钮,否则会显示剩余时间的消息。

$current_time = date('h:i A'); 
$time_start = date('h:i A', strtotime($r['time_start'])); 
$time_end = date('h:i A', strtotime($r['time_end'])); 

if($current_time is 15 mins before $time_start && $current_time < $time_end){ 
    //show clickable button 
}else{ 
    //show time remaining 
} 

enter image description here

请帮帮忙,逻辑/算法困惑我

回答

2

这是datetime对象变得非常方便:

$time_start = new DateTime($r['time_start']); 
$now = new DateTime(); 
$diff = $time_start->diff($now); 

if($diff->i < 15){ 
    // Do stuff 
} 
+0

嘿,你的工作,所以我选择了你的答案。你会向我解释$ diff = $ time_start - > diff($ now)的行以及它如何与15进行比较? – dresdain

+0

DateTime对象具有“diff”方法。基本上,当你在对象上调用diff并将另一个DateTime对象作为参数传入时,它会返回一个[DateInterval](http://www.php.net/manual/en/class.dateinterval.php)对象。这包含有关作为对象属性的两个日期的差异的信息。 $ diff-> y是年差,$ diff-> m是月份的差异等... – Scopey

2

不要比较字符串,比较时间戳。 time()是你的朋友。

$diff = time() - strtotime($r['time_start']); 
if($diff < 0) 
    ..too late, exam has started 
elseif($diff > 15*60) 
    ..more than 15 minutes remaining 
else 
    ..between 15 minutes and on time 

使用DateTime也将工作,但只是大矫枉过正简单地比较2点基本的时间戳。

-1
$time = time() 
if(($time > strtotime("2:15pm")) && ($time < strtotime("2:30pm")){ 
    //Display button 
}else{ 
    //Show time remaining 
}