I've seen a few examples using PHP but I am having some issues since I'm not too familiar with PHP and am on a time constraint.
I want to create a timestamp in which depending how long ago a post was created, it would display a different timestamp.
This is what I want:
If post was created less than a second ago, display: <1m;
If post was created between 1-59min ago, display : //# of minutes// + "m";
If post was created less than 1-24hrs ago, display: //# of hours// + "h";
If post was created 1-6 days ago, display: //# of days// + "d";
If post was created 1-3 weeks ago, display: //# of weeks// + "w";
If post was created 1-12 months ago, display: //# of months// + "m";
Here's the code I tried using:
function formatTime(timeCreated){
var periods = ["second", "minute", "hour", "day", "week", "month", "year", "decade"];
// var actualPeriods = ["m", "h", "d", "w", "m", "y"]
var lengths = ["60","60","24","7","4.35","12","10"]
var currentTime = Date.now()
var difference = currentTime - timeCreated;
for (var i = 0; difference >= lengths[i] && i < (lengths.length)-1; i++) {
difference = difference /lengths[i];
}
difference = Math.round(difference)
return difference + periods[i]
}
but formatTime(1508189037313)
is returning 74year
.
(1508189037313 is Mon 16 Oct 2017 16:23:57)
I saw an example that uses this in 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',
'd' => 'day',
'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';
}
but wasn't sure how to convert ->
and =>
over to javascript.
Any help would be appreciated. Thank you!