Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

javascript time ago function

function timeSince(date) {

  var seconds = Math.floor((new Date() - date) / 1000);

  var interval = seconds / 31536000;

  if (interval > 1) {
    return Math.floor(interval) + " years";
  }
  interval = seconds / 2592000;
  if (interval > 1) {
    return Math.floor(interval) + " months";
  }
  interval = seconds / 86400;
  if (interval > 1) {
    return Math.floor(interval) + " days";
  }
  interval = seconds / 3600;
  if (interval > 1) {
    return Math.floor(interval) + " hours";
  }
  interval = seconds / 60;
  if (interval > 1) {
    return Math.floor(interval) + " minutes";
  }
  return Math.floor(seconds) + " seconds";
}
var aDay = 24*60*60*1000;

console.log(timeSince(new Date(Date.now()-aDay)));
console.log(timeSince(new Date(Date.now()-aDay*2)));
Comment

PREVIOUS NEXT
Code Example
Javascript :: jquery to set value in select2 dropdown button 
Javascript :: javascript button onclick 
Javascript :: assert.match() nodejs 
Javascript :: how to replace word from string in javascript 
Javascript :: jquery change span tag text 
Javascript :: how to clone a object in javascript angular 
Javascript :: javascript get bounding rect 
Javascript :: jquery number format comma 
Javascript :: addAtribute 
Javascript :: nuxt dev server does not work on local network 
Javascript :: negative reciprocal javascript 
Javascript :: how to push the get variables without page reloading in Jquery 
Javascript :: how to find duplicate item in array of object in javascript 
Javascript :: current time in javascript 
Javascript :: within range js 
Javascript :: how to sort a populated data in mongoose 
Javascript :: javascript calculate days between dates 
Javascript :: javascript uppercase first letter of each word 
Javascript :: javascript get element by multiple class 
Javascript :: js does forEach respect order 
Javascript :: react post request 
Javascript :: how to put variable in string javascript 
Javascript :: check truthy or falsy javascript 
Javascript :: queryselector attribute 
Javascript :: node run parameters 
Javascript :: stampare una variabile in javascript 
Javascript :: how remove child in jquery 
Javascript :: sort array with objects 
Javascript :: divide array of objects to 4 arrays js 
Javascript :: dynamics js search another entity 
ADD CONTENT
Topic
Content
Source link
Name
5+7 =