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:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.