简体   繁体   English

计算两个日期之间的过渡时间时发生意外(负时间)-PHP和MySQL

[英]Unexpected (negative time) when calculating the elpased time between two dates - php and mysql

I want to get difference in seconds between the current date and certain date which is stored in a database as DATETIME type. 我想获得当前日期和某些日期之间以秒为单位的差异,该日期以DATETIME类型存储在数据库中。 I'm getting this date with this function: 我通过这个功能得到这个日期:

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];
}

In a another code, I call this function: 在另一个代码中,我调用此函数:

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

What's weird is that I'm getting a negative value . 奇怪的是我得到了负值

If you are getting a negative answer to "now - then", then "then" is in the future. 如果您对“现在-那么”的回答是否定的,那么将来是“那么”。

To confirm, try echo $date . 要确认,请尝试echo $date

If the difference is fairly small, then it means your database and PHP processes are not using the same timezone. 如果差异很小,则意味着您的数据库和PHP进程未使用相同的时区。 Be sure to set date_default_timezone_set in PHP, and SET time_zone = ... in MySQL, to the same identifier. 确保将PHP中的date_default_timezone_set和MySQL中的SET time_zone = ...为相同的标识符。

Use this approach: 使用此方法:

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

Note: Be sure, that you are executing the functions with right parameters. 注意:确保使用正确的参数执行功能。

In your case: 在您的情况下:

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

Sources: 资料来源:

  1. date() function date()函数
  2. strtotime() function strtotime()函数
  3. method source 方法来源

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM