0

I want to get difference between 2 timestamps of format Y-m-d H:i:s in minutes in PHP. The code used is,

$currentDate = date('Y-m-d H:i:s');
$userLastActivity = date($date);
$timeLapse = (($currentDate - $userLastActivity)/60);

Here, $date is obtained from database. The value of $timeLapse is 0 in output. Please help.

prashant0205
  • 269
  • 1
  • 3
  • 17

3 Answers3

4

Try using unix timestamp. Practically it measures the time in seconds from 1/1/1970 and it's a lot easier to use and understand than a php object.

$currentTimestamp = new DateTime()->getTimestamp();
$userLastActivity = date($date)->getTimestamp();
$timeLapse = (($currentDate - $userLastActivity)/60);

You should have the time saved as timestamp on the server too, in that case you could use the $date directly as a number, with no need for a conversion. And also, because it's universal, you can pass it around to javascript or any other language without any worries for conversion

Mihai Popescu
  • 386
  • 1
  • 11
0

Use strtotime to parse textual datetime into a Unix timestamp and substract $userLastActivity from $currentDate and divide by 60.

See if this helps -

<?php
$currentDate = strtotime(date('Y-m-d H:i:s'));
$date = "2016-10-11 02:40:50";
$userLastActivity = strtotime($date);
echo round(abs($currentDate - $userLastActivity) / 60). " minutes";
?>

For more details :strtotime

pradeep1991singh
  • 8,185
  • 4
  • 21
  • 31
-1

Change these 2 lines for a start, as I don't think dividing dates by 60 is gonna work to well.

$currentDate = time();
$userLastActivity = strtotime($date);

That way you have time stamps and not dates (string)

ArtisticPhoenix
  • 21,464
  • 2
  • 24
  • 38
  • Your second example is very wrong. That $interval->i is only returning the remaining minutes out of 60. You have to calculate the days, hours, minutes and seconds into minutes if you want to use diff function. – M H Jul 31 '17 at 20:05
  • @MichaelHanon - I don't feel like fixing it, it was [optional] stuff anyway. That's what I get for coding just in my head. Besides I think the question was changed sense I posted this.. ie `date($date)->getTimestamp()` syntax error call to method on non-object – ArtisticPhoenix Jul 31 '17 at 20:50