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

StackOverflow https://stackoverflow.com/questions/23569921

  •  19-07-2023
  •  | 
  •  

Вопрос

I want to get difference in seconds between the current date and certain date which is stored in a database as DATETIME type. 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.

If the difference is fairly small, then it means your database and PHP processes are not using the same timezone. Be sure to set date_default_timezone_set in PHP, and SET time_zone = ... in MySQL, to the same identifier.

Другие советы

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
  2. strtotime() function
  3. method source

Demo

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top