【问题标题】:Unexpected (negative time) when calculating the elpased time between two dates - php and mysql计算两个日期之间经过的时间时出现意外(负时间) - php和mysql
【发布时间】:2014-05-09 16:44:17
【问题描述】:

我想获取当前日期和以DATETIME 类型存储在数据库中的某个日期之间的秒数差异。我用这个函数得到这个日期:

function get_date_last_action($username)
{
    $id = $this->get_username_id($username);
    $query = "SELECT date_last_action".
             "FROM user".
             "WHERE user.id ='" . $id . "'";
    $result = mysql_query($query);
    $date_last_action = mysql_fetch_array($result);
    return $date_last_action[0];
}

在另一个代码中,我调用了这个函数:

$date = $h_db_functions->get_date_last_action("user1"); 
$currentTime = time();
$timeInPast = strtotime($date);
$differenceInSeconds = $currentTime - $timeInPast;

奇怪的是我得到了一个负值

【问题讨论】:

  • 你能做一个var_dump($date);吗?

标签: php mysql datetime


【解决方案1】:

如果您对“现在 - 那么”的回答是否定的,那么“那么”就是未来。

要确认,请尝试echo $date

如果差异很小,则意味着您的数据库和 PHP 进程没有使用相同的时区。请务必将 PHP 中的 date_default_timezone_set 和 MySQL 中的 SET time_zone = ... 设置为相同的标识符。

【讨论】:

    【解决方案2】:

    使用这种方法:

    $timeFirst  = strtotime('2014-04-15 18:20:20');
    $timeSecond = strtotime('2014-04-11 18:20:20');
    $differenceInSeconds = $timeSecond - $timeFirst;
    

    注意:请确保您正在使用正确的参数执行函数。

    在你的情况下:

    $currentTime = time();
    $timeInPast = strtotime($date); // date should be in YYYY-DD-MM HH:MM:SS format
    $result = $currentTime - $timeInPast;
    

    来源:

    1. date() function
    2. strtotime() function
    3. method source

    Demo

    【讨论】:

    • 日期返回一个字符串。
    • strtotime(date('Y-m-d H:i:s')) = time() = OP 已经写了这个。
    • @Dexa :) 谢谢。再次更新。忘记这个:)
    猜你喜欢
    • 2013-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-31
    • 1970-01-01
    • 2012-04-10
    • 2012-12-01
    • 2010-09-17
    相关资源
    最近更新 更多