我已经使用了在另一个问题上找到的一些代码。
<?
$start_date = new DateTime('now');
$timestamp = strtotime( $nt['last_seen'] );
$since_start = $start_date->diff($timestamp);
echo $since_start->i.' minutes<br>';
echo $since_start->s.' seconds<br>';
?>
这似乎不起作用?时间戳是从格式的mysql语句中提取的。
yyyy-mm-dd hh:mm:ss
答案 0 :(得分:2)
diff()
方法中的第一个参数需要一个DateTime
对象,但是你提供的是一个Unix时间戳。
请改用以下代码:
$start_date = new DateTime('now');
$end_date = new DateTime($nt['last_seen']);
$since_start = $start_date->diff($end_date);
echo $since_start->format('%i').' minutes<br>';
echo $since_start->format('%s').' seconds<br>';
正如Glavić在下面的评论中指出的那样,也可以从Unix时间戳创建一个DateTime
对象:
$date = new DateTime("@$timestamp"); // $timestamp is astring -- eg: 1382025097
但在这种情况下没有必要,第一种方法应该可以正常工作。
答案 1 :(得分:1)
$start_date = new DateTime('now');
$timestamp = new DateTime($nt['last_seen']);
$since_start = $start_date->diff($timestamp);
echo $since_start->format('%m').' minutes<br>';
echo $since_start->format('%s').' seconds<br>';
您需要将$ timestamp转换为新的DateTime,如上所述
我有几个我使用的包装器函数看看db date diff一个sql查询如果你从数据库中提取你的$ timestamp然后没有理由你不能在你的主查询中做差异并完全删除需要在PHP之后用PHP完成。
/**
* Date Diff between now and submitted data
* @param - $date - takes current date
* @return int number of days between inputted dates +ve numbers are start date in past -ve numbers are end date in future of now()
*/
function daves_date_diff($date) {
$start = new DateTime($date);
$today = new DateTime();
$diff = $start->diff($today);
return $diff->format('%d');
}
/**
* Database select based date diff as its more reliable than using php date diffs
* @param - $date - date string in mysql format of date to diff against
* @return - int - number of days date is different from now
*/
function db_date_diff($date) {
global $db;
$date = mysqli_real_escape_string($db->mysqli,$date);
$returneddiff = $db->queryUniqueObject("SELECT DATEDIFF('$date',NOW()) as DateDiff",ENABLE_DEBUG);
return $returneddiff->DateDiff;
}