0

我已经使用了一些已经在另一个问题上找到的代码。

<? 

$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
4

2 回答 2

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ć 在下面的评论中指出的那样,也可以DateTime从 Unix 时间戳创建对象:

$date = new DateTime("@$timestamp"); // $timestamp is astring -- eg: 1382025097

但在这种情况下没有必要,第一种方法应该可以正常工作。

于 2013-10-17T12:35:02.303 回答
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,那么您没有理由不能在主查询中执行 diff 并完全消除需要之后在 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;
}
于 2013-10-17T12:30:51.427 回答