JS TimeAgo – Format time e.g. “4 mins ago”

JS TimeAgo


function agoFun(min){
  const agoArr = [
  {str: "min", val: 1},
  {str: "hour", val: 60},
  {str: "day", val: 24},
  {str: "month", val: 30},
  {str: "year", val: 12}
  ];
  let temp = parseInt(min), agoStr;
  for( let i = 0; i < agoArr.length; i++ ){
    temp = Math.round(temp/agoArr[i].val);
    agoStr = temp > 1 ? agoArr[i].str+"s" : agoArr[i].str;
    if( agoArr[i+1] && temp < agoArr[i+1].val ){
      break;
    }
  }
  return (temp+" "+agoStr+" ago")
}

Demo Fiddle

Published by

Shiyam

My passion became my profession , I'm a driven, energetic and proactive tech professionally. I consider myself an engagement professional, as I don't simply provide solutions, I create them. I am a continuous learner – always looking for new technologies, in my spare time I search Google for the latest trends . I like to think of myself as a futurist and I'm a Full Stack JavaScript Developer.

Leave a comment