【问题标题】:Getting and Storing a timestamp difference using PHP and MySQL使用 PHP 和 MySQL 获取和存储时间戳差异
【发布时间】:2014-07-23 04:27:21
【问题描述】:

我正在为最终项目创建一个基本游戏;整个网站都已建成并准备就绪,但我无法让一个功能正常工作。

作用是随着时间的推移用户宠物的属性会降低。

您离开宠物的时间越长,它们的统计数据就会越低,直到它们“死亡”。到目前为止,我正在尝试使用以下代码计算登录之间的时间差:

$mod = mysqli_query($con,"select * from users where user_name='$user_name'");
while($row = mysqli_fetch_array($mod)){
    $last_login = $row['last_login'];
    $stored_login = $row['stored_login'];
    $time_diff = ($last_login-$stored_login);
    echo $time_diff;
    $time_mod = mysqli_query($con,"update users set time_mod='$time_diff' where user_name='$user_name'");                      
}

last_loginstored_login 都是 TIMESTAMP 变量,有人告诉我应该可以轻松地减去它们以获得解决方案。

但是,当我回显方程式时,它返回的只是0。我试过使用DATEDIFF,但 MySQL 给我一个错误,说我不能使用它。我只需要过去的天数 - 有什么办法可以做到这一点?

如果有帮助,您可以在此处访问测试版(创建帐户或登录):

http://www.eurogabby.com/MyPetMonster/login.php

username: a 
password: a

【问题讨论】:

  • last_loginstored_login 是时间戳格式?

标签: php mysql login timestamp project


【解决方案1】:

也许你可以试试。转换为该行的时间。

$last_login = strtotime($row['last_login']);
$stored_login = strtotime($row['stored_login']);
$time_diff = ($last_login - $stored_login);
echo $time_diff;

【讨论】:

    【解决方案2】:

    你只需要像这样使用 strtotime 转换时间

    $time_diff = (strtotime($last_login)-strtotime($stored_login));
    echo $time_diff;
    

    如果这不起作用,那么首先将它们转换为 strtotime 并存储在不同的变量中,然后像这样减去它们

    $last = strtotime($last_login);
    $stored = strtotime($stored_login);
    $time_diff = ($last-$stored);
    echo $time_diff;
    

    现在你可以像这样使用日期函数转换回时间

    $newtime = date("m/d/Y",$time_diff);
    echo $newtime = month/day/year
    

    请记住 m/d/y 将是您要转换的日期格式的选择。

    【讨论】:

    • 谢谢!我现在显示了一个值,但它是一个整数。如何将其转换回时间?
    • 好的,但现在看起来它没有存储任何信息。这可能是因为我当前更改字段之间只有几分钟的时间,但是我如何检查它是否正确存储? (它也呼应 00-00-0000)
    • 用于存储在数据库中将时间转换为数据库格式哪个日期('Y-m-d H:i:s')
    猜你喜欢
    • 2017-01-22
    • 2011-09-24
    • 1970-01-01
    • 2011-06-13
    • 2012-11-28
    • 2011-07-31
    • 2012-06-03
    • 1970-01-01
    • 2012-12-14
    相关资源
    最近更新 更多