我被困住了。我在datetime
表中有一个colummn comments
的数据库。基本上,当用户添加新评论时,它将被插入此表中并存储日期时间。所以我现在要做的就是检查是否,自从他上次评论以来已经过了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
Ok obviusly $limit->time
比$stamp
更为敏捷。使用time()
很简单time() + 60
,但如何使用datetime执行此操作?
答案 0 :(得分:0)
我认为这是你想做的事:
<?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.";
}
?>