Convert Milliseconds to Timestamp "Time Ago" (59m, 5d, 3m, etc) in Javascript

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!

2 answers

  • answered 2017-11-12 20:09 James

    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));

  • answered 2017-11-12 20:37 Dres

    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";
    }