0

I have utilised some code already found on another question.

<? 

$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>';

?>

This does not seem to work ?? the timestamp is pulled in from mysql statement in the format.

yyyy-mm-dd hh:mm:ss
Matt Leyland
  • 2,149
  • 3
  • 15
  • 16

2 Answers2

2

The first parameter in diff() method expects a DateTime object, but you're supplying a Unix timestamp instead.

Use the following code instead:

$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>';

Demo!


As Glavić notes in the comment below, it's possible to create a DateTime object from a Unix timestamp, too:

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

But it is not necessary in this case, and the first method should work just fine.

Amal Murali
  • 75,622
  • 18
  • 128
  • 150
  • If `strtotime` can convert to timestamp, then DateTime should also `new DateTime($nt['last_seen'])`. Plus, DateTime can accept timestamp like `new DateTime('@timestampNumber')` – Glavić Oct 17 '13 at 14:54
  • 1
    @Glavić: I didn't test the code before posting. Updated the answer, thanks :) – Amal Murali Oct 17 '13 at 15:53
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>';

you need to cast your $timestamp as a new DateTime something like the above

I have a couple of wrapper functions I use look at the db date diff one sql query if you're pulling your $timestamp from the database then there's no reason you can't do the diff in your master query and completely remove the need to do it in PHP after.

/** 
* 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;
}
Dave
  • 3,280
  • 2
  • 22
  • 40