php - Add time to datetime and check in if statement -
i stuck. have database colummn datetime in comments table. basicly when user adds new comment it's inserted in table , datetime stored. want check if, lets 1 minute passed since last commented. getting time true in if statement. well. before posted did last check. output not expected. code.
$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 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 smaler $stamp. time() it's simple, time() + 60 how datetime?
i think want do:
<?php date_default_timezone_set('utc'); // current datetime. $now = new datetime("now"); // last comment datetime. $comment = new datetime('2014-03-18 13:26:00'); // interval limit between comments. $limit = new dateinterval('pt1m'); // calculate difference between current , last commented datetime. $diff = $now->diff($comment); // calculate 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 difference? next comment allowed. if($limit->i <= $minutes) { echo "your comment has been saved!"; } else { echo "your aren't allowed comment now. wait ".intval($limit->i*60 - $diff->format('%s'))." seconds until allowed comment again."; } ?> edit: added missing calculation of total minutes. otherwise calculation don't work dates same minutes other day or hour.
another , simpler/generic (working every interval) solution this:
<?php date_default_timezone_set('utc'); // current datetime. $now = new datetime("now"); // last comment datetime. $comment = new datetime('2014-03-18 16:45:00'); // , add interval limit 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 difference? next comment allowed. if($comment <= $now) { echo "your comment has been saved!"; } else { echo "your aren't allowed comment now. on ".$comment->format('y-m-d h:i:s')." allowed comment again."; } ?>
Comments
Post a Comment