UNPKG

@videsk/humanize-date

Version:

Humanize dates making readable in locale and ultra lightweight

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