title: Javascript convert current time to timeago
body: <p>I have been trying to convert the current time to timeago like facebook and twitter have (2 min ago, 30sec ago). For that, I am taking the current time and with the help of function converting it to approx time. The code is below:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>var current = new Date();
  console.log(timeDifference(current, new Date(2018, 03, 27, 10, 30, 00, 00)));
  console.log(timeDifference(current, new Date(2018, 03, 27, 10, 00, 00, 00)));
  
  function timeDifference(current, previous) {
  
    var msPerMinute = 60 * 1000;
    var msPerHour = msPerMinute * 60;
    var msPerDay = msPerHour * 24;
    var msPerMonth = msPerDay * 30;
    var msPerYear = msPerDay * 365;
  
    var elapsed = current - previous;
  
    if (elapsed &lt; msPerMinute) {
      return Math.round(elapsed / 1000) + ' seconds ago';
    } else if (elapsed &lt; msPerHour) {
      return Math.round(elapsed / msPerMinute) + ' minutes ago';
    } else if (elapsed &lt; msPerDay) {
      return Math.round(elapsed / msPerHour) + ' hours ago';
    } else if (elapsed &lt; msPerMonth) {
      return 'approximately ' + Math.round(elapsed / msPerDay) + ' days ago';
    } else if (elapsed &lt; msPerYear) {
      return 'approximately ' + Math.round(elapsed / msPerMonth) + ' months ago';
    } else {
      return 'approximately ' + Math.round(elapsed / msPerYear) + ' years ago';
    }
  }</code></pre>
  </div>
  </div>
  </p>
  
  <p>But, it is not working correctly and I can't seem to know why?</p>