UNPKG

@videsk/humanize-date

Version:

Humanize dates making readable in locale and ultra lightweight

2 lines (1 loc) 2.61 kB
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).HumanizeDate=e()}(this,(function(){return class{constructor(){this.from=new Date,this.to=new Date,this.units={seconds:this.seconds,minutes:this.minutes,hours:this.hours,days:this.days,weeks:this.weeks,months:this.months,years:this.years,quarters:this.quarters,auto:this.auto}}toLocale(t=new Date,e={year:"numeric",month:"long",day:"numeric"}){return new Date(t).toLocaleDateString(navigator.language,e)}dates(t=new Date,e=new Date){const{from:s,to:i}=this.constructor.getDates(t,e);return this.from=new Date(s),this.to=new Date(i),this}within(t="seconds",e={numeric:"auto"}){if(!(t in this.units))throw new Error(`The available units are ${Object.keys(this.units)}`);return new Intl.RelativeTimeFormat(navigator.language,e).format(Math.floor(this.units[t](this.from,this.to)),"auto"!==t?t:this.autoToUnitText(this.from,this.to))}ago(t="seconds",e={numeric:"auto"}){if(!(t in this.units))throw new Error(`The available units are ${Object.keys(this.units)}`);return new Intl.RelativeTimeFormat(navigator.language,e).format(Math.floor(-1*this.units[t](this.from,this.to)),"auto"!==t?t:this.autoToUnitText(this.from,this.to))}seconds(t,e){return Math.abs(new Date(e||this.to)-new Date(t||this.from))/1e3}minutes(t,e){return Math.abs(new Date(e||this.to)-new Date(t||this.from))/6e4}hours(t,e){return Math.abs(new Date(e||this.to)-new Date(t||this.from))/36e5}days(t,e){return Math.abs(new Date(e||this.to)-new Date(t||this.from))/864e5}weeks(t,e){return Math.abs(new Date(e||this.to)-new Date(t||this.from))/24192e5}months(t,e){return Math.abs(12*this.years(t,e)+(new Date(e||this.to).getMonth()-new Date(t||this.from).getMonth()))}years(t,e){return Math.abs(new Date(e||this.to).getFullYear()-new Date(t||this.from).getFullYear())}quarters(t,e){return Math.abs(this.months(t,e)/4)}auto(t,e){return this.seconds(t,e)<=60?this.seconds(t,e):this.minutes(t,e)<=60?this.minutes(t,e):this.hours(t,e)<=24?this.hours(t,e):this.days(t,e)<=31?this.days(t,e):this.months(t,e)<=12?this.months(t,e):this.years(t,e)}autoToUnitText(t,e){return this.seconds(t,e)<=60?"seconds":this.minutes(t,e)<=60?"minutes":this.hours(t,e)<=24?"hours":this.days(t,e)<=31?"days":this.months(t,e)<=12?"months":"years"}static getDates(t,e){return!Array.isArray(t)&&"object"!=typeof t||"object"==typeof t&&"getTime"in t?{from:t,to:e}:Array.isArray(t)?{from:t[0],to:t[1]}:"object"==typeof t?{from:t[Object.keys(t)[0]],to:t[Object.keys(t)[1]]}:void 0}}}));