rago
Version:
A utility helper to calculate "time ago" or "from now " in a readable format using Intl API
2 lines (1 loc) • 887 B
JavaScript
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).rago={})}(this,(function(e){"use strict";const t=[["second",1],["minute",60],["hour",3600],["day",86400],["month",2592e3],["year",31104e3]];function n(e){const n=Math.round((e.valueOf()-Date.now())/1e3);for(let o=1;o<t.length;o+=1)if(Math.abs(n)<t[o][1]){const[e,i]=t[o-1];return{unit:e,delta:Math.round(n/i)}}return{delta:Math.round(n/31104e3),unit:"year"}}e.diffUnitFor=n,e.fromNow=function(e,t="en"){let o=e;if(!e)return"";if(!(e instanceof Date)&&(o=new Date(e),isNaN(o.getTime())))return"";const i=new Intl.RelativeTimeFormat(t,{style:"long",numeric:"auto"}),{delta:r,unit:u}=n(o);return i.format(r,u)},Object.defineProperty(e,"__esModule",{value:!0}),e[Symbol.toStringTag]="Module"}));