lukeed-fromnow
Version:
An extremely lightweight javascript utility for calculating readable time differences from now and past or future dates.
11 lines • 944 B
JavaScript
/**
* fromNow.js v1.0.0
* http://www.lukeed.com
*
* Licensed under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*
* Copyright 2014, LUKEED
* http://www.lukeed.com
*/
function fromNow(e,t,n,r){t=typeof t!=="undefined"?t:10;n=typeof n!=="undefined"?n:false;r=typeof r!=="undefined"?r:false;var i=new Date(e)-new Date,s=Math.abs(i);var o=n&&i<0?" ago":"";var u=60*1e3,a=u*60,f=a*24,l=f*30,c=f*365;var h=Math.floor(s/c),p=Math.floor(s%c/l),d=Math.floor(s%l/f),v=Math.floor(s%f/a),m=Math.floor(s%a/u);var g=h>1?" years":" year",y=p>1?" months":" month",b=d>1?" days":" day",w=v>1?" hours":" hour",E=m>1?" minutes":" minute";var S=[h?h+g:null,p?p+y:null,d?d+b:null,v?v+w:null,m?m+E:null];var x=[],T=0;S.forEach(function(e,n){if(e!=null&&T<t){T++;x.push(e)}});var N=x.length;x=x.join(", ")+o;if(r&&N>1){var C=x.split(", ");if(N==2){return C.join(" and ")}else{C[N-1]="and "+C[N-1];return C.join(", ")}}else{return x}}