-1

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!

a--m
  • 4,716
  • 1
  • 39
  • 59
Dres
  • 1,449
  • 3
  • 18
  • 35
  • 1
    You're not going to be able to directly transition that code to JavaScript - it relies on specific functionality of PHP's DateTime class. Consider something like Moment.js: https://momentjs.com/docs/#/displaying/fromnow/ – ceejayoz Nov 12 '17 at 19:52
  • equivalent to associative array is an object literal. `{'y':'year',..., 's':'second'}` – charlietfl Nov 12 '17 at 19:53
  • Note there are many many resources found in a web search for doing this. – charlietfl Nov 12 '17 at 19:54
  • i'd love to use moment.js but unfortunately we can't :( – Dres Nov 12 '17 at 19:54
  • most of my web searches are pulling up php solutions.. and now i'm wording it differently and finding different solutions.. i'll post an answer once i get the solution. let's try again! – Dres Nov 12 '17 at 19:56
  • 1
    well you won't pull up php solutions if you use the word *"javascript"* in the search – charlietfl Nov 12 '17 at 20:09

2 Answers2

6

Create some structure that stores the number of milliseconds for the various periods, subtract the date you're interested in from Date.now(), build an if structure checking to see if the difference is greater than the break point for the periods (from biggest to smallest) - then format some kind of output. If nothing matches you can return something indicating that it was more recent than one minute.

Note that the symbol you're using for minutes and months is the same.

var periods = {
  month: 30 * 24 * 60 * 60 * 1000,
  week: 7 * 24 * 60 * 60 * 1000,
  day: 24 * 60 * 60 * 1000,
  hour: 60 * 60 * 1000,
  minute: 60 * 1000
};

function formatTime(timeCreated) {
  var diff = Date.now() - timeCreated;

  if (diff > periods.month) {
    // it was at least a month ago
    return Math.floor(diff / periods.month) + "m";
  } else if (diff > periods.week) {
    return Math.floor(diff / periods.week) + "w";
  } else if (diff > periods.day) {
    return Math.floor(diff / periods.day) + "d";
  } else if (diff > periods.hour) {
    return Math.floor(diff / periods.hour) + "h";
  } else if (diff > periods.minute) {
    return Math.floor(diff / periods.minute) + "m";
  }
  return "Just now";
}
console.log(formatTime(Date.now()));
console.log(formatTime(1510507151026));
console.log(formatTime(1510517051026));
console.log(formatTime(1508189037313));
James
  • 20,957
  • 5
  • 26
  • 41
1

Did some more research, asked the right google questions, found This question also answered here and added some edits to fit my needs!

function formatTime(timeCreated) {

  var diff = Math.floor((Date.now() - timeCreated) / 1000);
  var interval = Math.floor(diff / 31536000);

  if (interval >= 1) {
    return interval + "y";
  }
  interval = Math.floor(diff / 2592000);
  if (interval >= 1) {
    return interval + "m";
  }
  interval = Math.floor(diff / 604800);
  if (interval >= 1) {
    return interval + "w";
  }
  interval = Math.floor(diff / 86400);
  if (interval >= 1) {
    return interval + "d";
  }
  interval = Math.floor(diff / 3600);
  if (interval >= 1) {
    return interval + "h";
  }
  interval = Math.floor(diff / 60);
  if (interval >= 1) {
    return interval + " m";
  }
  return "<1m";
}
Dres
  • 1,449
  • 3
  • 18
  • 35
  • If this is your answer, please accept it. This would be a lot less code using `if (dif > 31536000) return 'y';` and so on. – RobG Nov 12 '17 at 22:35