UNPKG

rago

Version:

A utility helper to calculate "time ago" or "from now " in a readable format using Intl API

2 lines (1 loc) 581 B
const t=[["second",1],["minute",60],["hour",3600],["day",86400],["month",2592e3],["year",31104e3]];function e(e){const n=Math.round((e.valueOf()-Date.now())/1e3);for(let a=1;a<t.length;a+=1)if(Math.abs(n)<t[a][1]){const[e,r]=t[a-1];return{unit:e,delta:Math.round(n/r)}}return{delta:Math.round(n/31104e3),unit:"year"}}function n(t,n="en"){let a=t;if(!t)return"";if(!(t instanceof Date)&&(a=new Date(t),isNaN(a.getTime())))return"";const r=new Intl.RelativeTimeFormat(n,{style:"long",numeric:"auto"}),{delta:o,unit:u}=e(a);return r.format(o,u)}export{e as diffUnitFor,n as fromNow};