添加时间到datetime和检查if语句



我卡住了。我有一个数据库列datetimecomments表。基本上,当用户添加新评论时,它会插入到该表中,并存储日期时间。所以我现在要做的是检查,假设距离他上次评论已经过去了1分钟。但是在if语句中我总是得到真值。好。张贴这之前做了最后的检查。输出不符合预期。我的代码。

$limits = new Limits();
$user = new User();
$time = new DateTime();
$time->add(new DateInterval('PT' . 1 . 'M'));
$stamp = $time->format('Y-m-d H:i:s');
$limit = $limits->check_comment_limit($user->loggedInUser());
if($limit->time < $stamp){
echo 'Take a brake';
}
//for debugging
echo $stamp . '<br>';//2014-03-18 13:38:41
echo $limit->time; //2014-03-18 01:37:37

好,显然$limit->time小于$stamptime()很简单,time() + 60但如何用日期时间做到这一点?

我认为这是你想要做的:

<?php
 date_default_timezone_set('UTC'); 
 // Get current datetime.
 $now = new DateTime("now");
 // Get last comment datetime.
 $comment = new DateTime('2014-03-18 13:26:00');
 // Get interval limit between comments.
 $limit = new DateInterval('PT1M');
 // Calculate the difference between the current and last commented datetime.
 $diff = $now->diff($comment);
 // Calculate the total minutes.
 $minutes = $diff->days * 24 * 60;
 $minutes += $diff->h * 60;
 $minutes += $diff->i;
 // Debug output
 echo $now->format('Y-m-d H:i:s').'<br>';
 echo $comment->format('Y-m-d H:i:s').'<br>';
 echo $limit->i.'<br>';
 echo $minutes.' minutes <br>';
 // Limit smaller than difference? Next comment is allowed.
 if($limit->i <= $minutes) {
    echo "Your comment has been saved!";
 } else {
echo "Your aren't allowed to comment now. Wait ".intval($limit->i*60 - 
      $diff->format('%s'))." seconds until you are allowed to comment again.";
 }
 ?>

编辑:增加了总分钟的缺失计算。

另一个更简单/通用(适用于每个间隔)的解决方案是这样的:

<?php
date_default_timezone_set('UTC'); 
// Get current datetime.
$now = new DateTime("now");
// Get last comment datetime.
$comment = new DateTime('2014-03-18 16:45:00');
// Get and add interval limit to comments.
$limit = new DateInterval('PT1M');
$comment->add($limit);
// Debug output
echo $now->format('Y-m-d H:i:s').'<br>';
echo $comment->format('Y-m-d H:i:s').'<br>';
// Limit smaller than difference? Next comment is allowed.
if($comment <= $now) {
    echo "Your comment has been saved!";
} else {
    echo "Your aren't allowed to comment now. On ".$comment->format('Y-m-d H:i:s')." you 
            are allowed to comment again.";
}
?>

相关内容

  • 没有找到相关文章