title: Convert Milliseconds to Timestamp "Time Ago" (59m, 5d, 3m, etc) in Javascript
body: <p>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.</p>
  
  <p>I want to create a timestamp in which depending how long ago a post was created, it would display a different timestamp.</p>
  
  <p>This is what I want:</p>
  
  <ul>
  <li><p>If post was created less than a second ago, display: &lt;1m;</p></li>
  <li><p>If post was created between 1-59min ago, display : //# of minutes// +
  "m";</p></li>
  <li><p>If post was created less than 1-24hrs ago, display: //# of hours// +
  "h";</p></li>
  <li><p>If post was created 1-6 days ago, display: //# of days// + "d";</p></li>
  <li><p>If post was created 1-3 weeks ago, display: //# of weeks// + "w";</p></li>
  <li><p>If post was created 1-12 months ago, display: //# of months// + "m";</p></li>
  </ul>
  
  <p>Here's the code I tried using:</p>
  
  <pre><code>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 &gt;= lengths[i] &amp;&amp; i &lt; (lengths.length)-1; i++) {
      difference = difference /lengths[i];
    }
  
  
    difference = Math.round(difference)
  
    return difference + periods[i]
  }
  </code></pre>
  
  <p>but <code>formatTime(1508189037313)</code> is returning <code>74year</code>.</p>
  
  <p>(1508189037313 is Mon 16 Oct 2017 16:23:57)</p>
  
  <p>I saw an example that uses this in PHP</p>
  
  <pre><code>function time_elapsed_string($datetime, $full = false) {
      $now = new DateTime;
      $ago = new DateTime($datetime);
      $diff = $now-&gt;diff($ago);
  
      $diff-&gt;w = floor($diff-&gt;d / 7);
      $diff-&gt;d -= $diff-&gt;w * 7;
  
      $string = array(
          'y' =&gt; 'year',
          'm' =&gt; 'month',
          'w' =&gt; 'week',
          'd' =&gt; 'day',
          'h' =&gt; 'hour',
          'i' =&gt; 'minute',
          's' =&gt; 'second',
      );
      foreach ($string as $k =&gt; &amp;$v) {
          if ($diff-&gt;$k) {
              $v = $diff-&gt;$k . ' ' . $v . ($diff-&gt;$k &gt; 1 ? 's' : '');
          } else {
              unset($string[$k]);
          }
      }
  
      if (!$full) $string = array_slice($string, 0, 1);
      return $string ? implode(', ', $string) . ' ago' : 'just now';
  }
  </code></pre>
  
  <p>but wasn't sure how to convert <code>-&gt;</code> and <code>=&gt;</code> over to javascript.</p>
  
  <p>Any help would be appreciated. Thank you!</p>