首页 > 解决方案 > Check if the time is more than 24h and show it

问题描述

I have in my MSSQL database a column with datatype of datetime which contains some dates in this format 2021-01-11 19:58:04.277.

This is a voting system, the idea is that the users can only vote once every 24 hours.

Every time they vote this table is updated with a new record and a new date is added with the corresponding user.

I want to display a message that says how many hours left to place the next vote.

This is the code I am trying to use:

 /**
 * Get Votes Time
 * 
 */
public function getVoteRemainingTime($account) {
    date_default_timezone_get();
    $currentTime = date('Y-m-d H:i:s');

    $sql = "SELECT VoteDate FROM dbo.vote WHERE Account = :account ORDER BY logid DESC";
    $query = $this->db->prepare($sql);
    $query->execute(array(':account' => $account)); 
    $voteDate = $query->fetch(PDO::FETCH_OBJ);

    $timeLeftVote = strtotime($currentTime) - strtotime($voteDate->VoteDate);

    if($timeLeftVote > 86400) {
        return '<strong>Vote Available!</strong>';
    } else {
        return $timeLeftVote;
    }

}

But it is displaying the wrong information. What I am doing wrong? I would appreciate your help.

Thanks!

标签: phpsql-serverdatetimepdo

解决方案


因为我无法检查您的数据库查询,所以我只检查了其余代码,如果我用$voteDate->VoteDate静态日期替换它似乎可以工作(正如 Fikri F 在这篇文章的评论中提到的那样)。

所以请提供更多信息。您可以将数据库中的当前时间和上一次投票时间输出为字符串,并输出两个日期以及 strtotime 的结果,最后输出该方法的结果。然后请解释一下,错误的行为是什么。这样,我们可以将问题缩小到 DB 查询或 PHP 代码。(我会写这个作为评论,但我没有足够的声誉。)


推荐阅读