I am trying to convert a timestamp of the format 2009-09-12 20:57:19
and turn it into something like 3 minutes ago
with PHP.
I found a useful script to do this, but I think it's looking for a different format to be used as the time variable. The script I'm wanting to modify to work with this format is:
function _ago($tm,$rcs = 0) {
$cur_tm = time();
$dif = $cur_tm-$tm;
$pds = array('second','minute','hour','day','week','month','year','decade');
$lngh = array(1,60,3600,86400,604800,2630880,31570560,315705600);
for($v = sizeof($lngh)-1; ($v >= 0)&&(($no = $dif/$lngh[$v])<=1); $v--); if($v < 0) $v = 0; $_tm = $cur_tm-($dif%$lngh[$v]);
$no = floor($no);
if($no <> 1)
$pds[$v] .='s';
$x = sprintf("%d %s ",$no,$pds[$v]);
if(($rcs == 1)&&($v >= 1)&&(($cur_tm-$_tm) > 0))
$x .= time_ago($_tm);
return $x;
}
I think on those first few lines the script is trying to do something that looks like this (different date format math):
$dif = 1252809479 - 2009-09-12 20:57:19;
How would I go about converting my timestamp into that (unix?) format?
Just to throw in another option...
Whilst I prefer the DateTime method posting here, I didn't like the fact it displayed 0 years etc.
Many solutions here did not account for rounding. For example:
Event happened at 3pm two days ago. If you are checking at 2pm, it will show one day ago. If you are checking at 4pm it will show two days ago.
If you are working with unix time, this helps:
It is not perfect if you are worried about leap seconds and daylight savings time.
I don't know why nobody mention Carbon yet.
https://github.com/briannesbitt/Carbon
This is actually an extension to php dateTime (which was already used here) and it has: diffForHumans method. So all you need to do is:
more examples: http://carbon.nesbot.com/docs/#api-humandiff
Pros of this solution:
Here's my solution for a notification module I built some time ago. It returns output similar to Facebook's notifications dropdown (eg. 1 day ago, Just now, etc).
When we develop a message or notification system in our application where you need to show time like '1 hour ago', or 2 week ago etc. It is just calculating the time from current to post time of message
I answer here for previously asked question on this site xx time ago function doesn't work
I hope this will be helpful for you