prashant0205
prashant0205

Reputation: 279

Difference between timestamps in minutes in PHP

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.

Upvotes: 0

Views: 9721

Answers (3)

ArtisticPhoenix
ArtisticPhoenix

Reputation: 21661

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)

Upvotes: -1

pradeep1991singh
pradeep1991singh

Reputation: 8365

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

Upvotes: 0

Mihai Popescu
Mihai Popescu

Reputation: 396

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

Upvotes: 4

Related Questions