Sam
Sam

Reputation: 67

time subtract mysql and php

I want to find the time difference between a mysql timestamp and the time now in php.

$timesince = strtotime("now") -  $row['DateTime'];

This is my attempt at doing it but it doesn't seem to work.

Also, really ideally I'd like the output to be in a nice format like: 34 minutes ago,2 hours 5 minutes ago 4,days 2 minutes ago etc.

Really, really appreciate any help on this.

Upvotes: 5

Views: 4595

Answers (2)

Vic
Vic

Reputation: 1346

strtotime("now") returns the time as seconds since the Unix epoch, i.e. an integer. A mysql "timestamp" field is going to be YYYY-mm-dd HH:mm:ss. You first need to get those to be the same format. I'd recommend selecting the mysql timestamp field as UNIX_TIMESTAMP(DateTime) so it returns an integer, and then you'll be able to do your math to get $timesince in seconds.

Then, like @Derek Adair said, check out the PHP Date Object

Upvotes: 7

Derek Adair
Derek Adair

Reputation: 21925

Check out the manual for the PHP Date Object

simply using date() returns the current date.

Try something like...

$curDate = date();
$mysqlTimestamp = $row['timestamp'];

$dif = strtotime($curdate) - strtotime($mysqlTimestamp);

Upvotes: 2

Related Questions