【问题标题】:How do I check if something was 4 days ago in PHP?如何检查 PHP 中是否有 4 天前的内容?
【发布时间】:2012-05-10 11:22:24
【问题描述】:

我正在尝试编写一个函数来检查“已完成的课程”是否是四天前。例如,我如何检查所述课程是否在该时间范围内。如果昨天完成,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 日上完的课应该是真的吧?

【问题讨论】:

  • $finishedLesson['deadline'] 是什么数据类型,是 unix 时间戳吗?
  • 当您说 4 天前时,您是指正好在 4 天前和 5 天前之间(即 6:th 下午 1:27 和 7:th 下午 1:27 之间)还是做您是指 6 号当天的任何时间?

标签: php unix time


【解决方案1】:
$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

}

【讨论】:

  • 嘿,你的回答是正确的,而且比我的更有意义,但这之间有什么区别:$lastLessonDate + $fourDays > $time 和你的 if 语句?
  • 其实...我找到了 $lastLessonDate + $fourDays > $time to work !
【解决方案2】:

所有计算都应相对于今天上午 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';

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-30
    • 1970-01-01
    • 2011-07-19
    相关资源
    最近更新 更多