如何在PHP中检查4天前是否有问题?

时间:2012-05-10 11:22:25

标签: php unix time

我正在尝试编写一个功能,检查四天前是否有“完成的课程”。例如,如何检查所述课程是否在该时间范围内。如果它是在昨天,2天前,3天前,4天前完成的,那么它将在“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

}

现在,if语句一直是真正的,这不是我想要的,因为我有一个课程在5月3日结束。 5月7日的课程应该是真的吗?

2 个答案:

答案 0 :(得分: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

}

答案 1 :(得分:0)

所有计算都应该相对于今天上午12点计算,而不是time()现在给你当前时间(例如下午6点)这是一个问题,因为当你这样做时,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';