我希望在当前日期和特定日期之间以秒为单位,以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;
奇怪的是,我得到的是负值。
答案 0 :(得分:3)
如果你现在得到否定答案,那么现在 - 然后"然后"然后"是将来。
要确认,请尝试echo $date
。
如果差异相当小,那么这意味着您的数据库和PHP进程没有使用相同的时区。请务必将PHP中的date_default_timezone_set
和MySQL中的SET time_zone = ...
设置为相同的标识符。
答案 1 :(得分: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;
来源: