【问题标题】:Calculate the difference between timestamp计算时间戳之间的差异
【发布时间】:2012-07-04 08:42:54
【问题描述】:

我已经创建了注册页面,当用户单击提交按钮时,激活链接会发送到他的电子邮件,并且相应的时间戳会存储在数据库中。如果用户单击该激活链接,我必须检查该链接是在 24 小时之前还是之后单击的。 我的代码:-

function confirmEmail($activation_code){
        $this->load->database();
        $this->load->helper('date');
        echo "activation link will be checked and accordingly flag will be set.";
        $activation_sent_timestamp=$this->db->query("SELECT activation_timestamp FROM tbl_user_registration WHERE email_verification_code='$activation_code'");
        foreach($activation_sent_timestamp->result() as $res){
            $activation_time_from_db=$res->activation_timestamp;
        }
        echo $activation_time_from_db."\n\r";
        $now = time();
        $human = unix_to_human($now);
        echo $human;
        $difference = ($human-$activation_time_from_db);
        if($difference < 24) {
               echo "correct"
        }
        else echo "Link expired";
    }

我正在使用 codeigniter。我该怎么做,这段代码没有显示任何错误,但我不知道这是计算 24 小时的正确方法,我正在检查但没有得到任何东西。请检查代码。

已解决........ :)

【问题讨论】:

  • 建议:我总是尝试将 php 日期和 mysql 日期分开,因为有时会出现不匹配。如果您使用 NOW() 插入数据,则将 DATE_ADD 和 DATE_SUB 与 INTERVAL 1 DAY 一起使用。如果字段是日期时间,则使用 UNIX_TIMESTAMP() 对其进行转换。如果您使用 'time()' 插入,则可以使用 strtotime('+1 day')。

标签: php html database codeigniter timestamp


【解决方案1】:

unix_to_human() 只返回人类可读形式的时间戳

最简单的方法是,找出两个时间戳之间的差异,转换为hrs并检查是否小于24hrs

【讨论】:

  • 你说要这样做$sent_time=human_to_unix($activation_time_from_db); $now = time(); echo ($now-$sent_time);如何将这段时间转换为小时..?
【解决方案2】:

您可能想使用date_diff

请看这里:DATE_DIFF()

【讨论】:

    【解决方案3】:

    您可以使用 diff 计算差异,也可以更改时间格式

    $datetime1 = new DateTime('2009-10-11');
    $datetime2 = new DateTime('2009-10-13');
    $interval = $datetime1->diff($datetime2);
    echo $interval->format('%R%a days');
    

    【讨论】:

      【解决方案4】:

      将两个时间戳转换为 php date('Y-m-d') 格式,然后尝试 date_diff

      【讨论】:

        【解决方案5】:

        你可以在查询中使用mysql timediff函数。
        看看你的情况,你可以像我在这篇文章中回答的那样做到这一点

        Finding free blocks of time in mysql and php?

        【讨论】:

          【解决方案6】:
          $time = time();
          
          $seconds = 86400 // seconds of 24 Hours
          
          SELECT * FROM tbl_user_registration WHERE ( $time - UNIX_TIMESTAMP( activation_timestamp ) >= $seconds )
          

          【讨论】:

          • 显示清Undefined property: stdClass::$activation_timestamp错误。 :(
          • activation_timestamp 是你表的列名 if( count($activation_sent_timestamp->result()) ) { //你有过期的链接 }
          猜你喜欢
          • 1970-01-01
          • 2020-05-13
          • 1970-01-01
          • 2014-05-04
          • 2015-03-14
          • 1970-01-01
          相关资源
          最近更新 更多