date-diff-js
Version:
JavaScript library for getting difference between two dates
5 lines • 2.4 kB
JavaScript
(function(){function r(d){d=String(d);"M"!=d&&(d=d.toLowerCase());switch(d){case "years":case "year":case "yrs":case "yr":case "y":return"y";case "months":case "month":case "mon":case "m":return"m";case "days":case "day":case "dy":case "d":return"d";case "hours":case "hour":case "hrs":case "hr":case "h":return"h";case "minutes":case "minute":case "mins":case "min":case "M":return"M";case "seconds":case "second":case "secs":case "sec":case "s":return"s";case "milliseconds":case "millisecond":case "msecs":case "msec":case "ms":return"ms";
case "weeks":case "week":case "wks":case "wk":case "w":return"w";default:return!1}}function x(d){return"[object Date]"!==Object.prototype.toString.call(d)||isNaN(d.getTime())?!1:!0}function v(d,f,e){var a=new Date(d),b=new Date(f);x(a)||(a=new Date);x(b)||(b=new Date);a.getTime()>b.getTime()&&(f=a,a=b,b=f);var g=Date.UTC(a.getFullYear(),a.getMonth(),a.getDate(),a.getHours(),a.getMinutes(),a.getSeconds()),k=Date.UTC(b.getFullYear(),b.getMonth(),b.getDate(),b.getHours(),b.getMinutes(),b.getSeconds());
f=k-g;d=Math.floor(f/1E3);var m=Math.floor(d/60),n=Math.floor(m/60),p=Math.floor(n/24),t=Math.floor(p/7),c=n-24*p,h=m-60*n,r=d-60*m,v=f-1E3*d,z=p-7*t,w=Date.UTC(a.getFullYear(),a.getMonth(),a.getDate()),q=Date.UTC(b.getFullYear(),b.getMonth(),b.getDate()),l=0;g-w>k-q&&(l=1);w=a.getYear();g=a.getMonth();a=a.getDate();var u=b.getYear();k=b.getMonth();q=b.getDate();b={};var y=[31,28,31,30,31,30,31,31,30,31,30,31];1==function(){if(0!==(u&3))return 0;if(0!==u%100||0===u%400)return 1}&&(y[2]=29);b=u-w;
k>=g?g=k-g:(b--,g=12+k-g);q>=a?l=q-a-l:(g--,l=y[k]+q-a-l,0>g&&(g=11,b--));a=12*b+g;c={years:0,months:0,weeks:0,days:p,hours:c,minutes:h,seconds:r,milliseconds:v};h=p;"Y"==e||"y"==e?(h=b,c.years=b,c.months=g,c.days=l):"m"==e?(h=a,c.months=a,c.days=l):"W"==e||"w"==e?(h=t,c.weeks=t,c.days=z):"H"==e||"h"==e?(h=n,c.days=0,c.hours=n):"M"==e?(h=m,c.minutes=m,c.hours=0,c.days=0):"S"==e||"s"==e?(h=d,c.seconds=d,c.minutes=0,c.hours=0,c.days=0):"MS"==e||"ms"==e?(h=f,c.milliseconds=f,c.seconds=0,c.minutes=0,
c.hours=0,c.days=0):e="d";return b={input:e,output:h,outputs:c,totals:{years:b,months:a,weeks:t,days:p,minutes:m,hours:n,seconds:d,milliseconds:f}}}module.exports=function(d,f,e){d=void 0===d?new Date:d;var a;e="undefined"===typeof e?"d":e;if("undefined"===typeof f)f=new Date;else if(a=r(f))f=new Date,e=a;else if(a=r(e))e=a;return v(d,f,e)}})();