2012-05-10 35 views
0

我想寫一個函數來檢查一個「完成的課程」是否在四天前。例如,如何檢查課程是否在該時間範圍內。如果它是在昨天,2天前,3天前,4天前完成的,那麼它是在「4天前」的時間範圍內。如何在PHP中檢查4天前是否有東西?

如何檢查?

到目前爲止,我已經做了:

$time = time(); 

$fourDays = 345600; 
$threeDays = 259200; 
$lastLesson = $ml->getLesson($cid, $time, true); 

$lastLessonDate = $lastLesson['deadline']; 
$displayLastLesson = false; 
if ($lastLessonDate + $fourDays < $time) 
{ 
    $displayLastLesson = true; 
    //We print lesson that was finished less than 4 days ago 
} 
else 
{ 
    //We print lesson that is in the next 3 days 

} 

眼下,如果語句保持擊球真的,是不是我想要的,因爲我有一個在5月3日結束的一課。 5月7日結束的課程應該是真的嗎?

+0

什麼數據類型爲$ finishedLesson [ '最後期限'],它是一個UNIX時間戳? – gunnx

+0

'strtotime(' - 4 days')' – Sarfraz

+0

當你說4天前,你的意思是正好在4天前和5天前(即在6:1下午1:27和7: th)還是你的意思是在6日的任何時候? –

回答

2
$time = time(); 
$fourDays = strtotime('-4 days'); 
$lastLesson = $ml->getLesson($cid, $time, true); 

$lastLessonDate = $finishedLesson['deadline']; 
$displayLastLesson = false; 
if ($lastLessonDate >= $fourDays && $lastLessonDate <= $time) 
{ 
    $displayLastLesson = true; 
    //We print lesson that was finished less than 4 days ago 
} 
else 
{ 
    //We print lesson that is in the next 3 days 

} 
+0

嘿,你的回答是正確的,比我的更有意義,但這與之間有什麼區別: $ lastLessonDate + $ fourDays> $ time和你的if語句? –

+0

其實......我找到了$ lastLessonDate + $ fourDays> $時間來工作! –

0

所有的計算應相對於在今天上午12點來計算,而不是time()現在給你當前時間(例如下午6:00)。這是因爲,當你做到這一點,1天前(現在 - 24小時)的問題的手段時間是在昨天下午6點到今天下午6點之間。相反,昨天應該是昨天早上12點到今天早上12點之間的時間。

下面是一個簡單的計算來說明這個想法:

$lastLessonDate = strtotime($lastLessonDate); 
$today = strtotime(date('Y-m-d')); // 12:00am today , you can use strtotime('today') too 
$day = 24* 60 * 60; 
if($lastLessonDate > $today) // last lesson is more than 12:00am today, meaning today 
echo 'today'; 
else if($lastLessonDate > ($today - (1 * $day)) 
echo 'yesterday'; 
else if($lastLessonDate > ($today - (2 * $day)) 
echo '2 days ago'; 
else if($lastLessonDate > ($today - (3 * $day)) 
echo '3 days ago'; 
else if($lastLessonDate > ($today - (4 * $day)) 
echo '4 days ago'; 
else 
echo 'more than 4 days ago'; 
相關問題