Say I have some posts and they all have the time they were submitted.
Now what I want to do is check how long ago they were posted in minutes. For example post 1 was posted 40 minutes ago and post 2 was posted 479 minutes ago and so on…
And of course I would run that $data
array in a loop but for the time being its understandable. And also the time includes a timestamp so instead of just the time it includes the date and time.
php:
$data = ["POST1"=>"3:10PM","POST2"=>"3:40PM","POST3"=>"4:20PM","POST4"=>"5:15PM"]
html:
<div>
<p><?php echo $data[0] ?><p>
</div>
Here is what would help you:
<?php
function time_elapsed_string($datetime, $full = false) {
$now = new DateTime;
$ago = new DateTime($datetime);
$diff = $now->diff($ago);
$diff->w = floor($diff->d / 7);
$diff->d -= $diff->w * 7;
$string = array(
'y' => 'year',
'm' => 'month',
'w' => 'week',
'h' => 'hour',
'i' => 'minute',
's' => 'second',
);
foreach ($string as $k => &$v) {
if ($diff->$k) {
$v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
} else {
unset($string[$k]);
}
}
if (!$full) $string = array_slice($string, 0, 1);
return $string ? implode(', ', $string) . ' ago' : 'just now';
}
$date = date_parse_from_format('Y-d-m H:i:s', '2014-02-05 5:22:35');
$unixTimestamp = mktime(
$date['hour'], $date['minute'], $date['second'],
$date['month'], $date['day'], $date['year']
);
echo time_elapsed_string(date('Y-m-d H:i:s',$unixTimestamp), false);
and here is a working fiddle for you.