-3

I pull a time stamp off the database with a query, How can I compare that time stamp with the current time. I am trying to make the output say, "Updated X minutes ago".

The format of the time stamp off the server is YYYY-MM-DD HH-MM-SS (24hr system)

Thanks!

socbrian
  • 151
  • 1
  • 2
  • 8

2 Answers2

3

You can convert most dates (including those sourced from MySQL) with strtotime() into a unix timestamp (a count of the seconds since Jan 1st 1970)

So you could do

$then = $your_date_from_mysql;
$now = time();
$time_ago = $now - strtotime($then); //gets time ago in seconds
$minutes = $time_ago / 60; //you could call floor() on this to round it down - or ceil() to round up
echo "Updated {$minutes} minutes ago";
solarise
  • 453
  • 2
  • 3
1

Assuming you're using MySQL:

SELECT UNIX_TIMESTAMP(now()) - UNIX_TIMESTAMP(timestampfield) AS seconds

and then

echo "Updated ", ceil($seconds / 60), " seconds ago";

It's better to have the database do the computing - it's already got the timestamp in an internal format that's easily amenable to these sorts of calculations. Selecting out a formatted string, then converting the string back to a time value, etc... is just a waste of computing time.

Marc B
  • 356,200
  • 43
  • 426
  • 500