UNPKG

ilib

Version:

iLib is a cross-engine library of internationalization (i18n) classes written in pure JS

2 lines 20.4 kB
// !data dateformats sysres var ilib=require("../index.js"),Utils=require("./Utils.js"),JSUtils=require("./JSUtils.js"),Locale=require("./Locale.js"),LocaleInfo=require("./LocaleInfo.js"),IDate=require("./IDate.js"),DateFactory=require("./DateFactory.js"),CalendarFactory=require("./CalendarFactory.js"),ResBundle=require("./ResBundle.js"),TimeZone=require("./TimeZone.js"),GregorianCal=require("./GregorianCal.js"),ISet=require("./ISet.js"),DateFmt=function(options){var c,comps,loadParams,sync=!0;if(this.locale=new Locale(),this.type="date",this.length="s",this.dateComponents="dmy",this.timeComponents="ahm",this.meridiems="default",this.useIntl=!1,(options=options||{sync:!0}).locale&&(this.locale="string"==typeof options.locale?new Locale(options.locale):options.locale),!options.type||"date"!==options.type&&"time"!==options.type&&"datetime"!==options.type||(this.type=options.type),options.calendar&&(this.calName=options.calendar),!options.length||"short"!==options.length&&"medium"!==options.length&&"long"!==options.length&&"full"!==options.length||(this.length=options.length.charAt(0)),options.date){for(var arr=options.date.split(""),dateComps=new ISet(),bad=!1,i=0;i<arr.length;i++)if("d"!==(c="e"===(c=arr[i].toLowerCase())?"w":c)&&"m"!==c&&"y"!==c&&"w"!==c&&"n"!==c){if("h"!==c&&"m"!==c&&"s"!==c&&"a"!==c&&"z"!==c&&"g"!==c){bad=!0;break}}else dateComps.add(c);bad||(comps=dateComps.asArray().sort(function(left,right){return left<right?-1:right<left?1:0}),this.dateComponents=comps.join(""))}if(options.time){arr=options.time.split("");var timeComps=new ISet();for(this.badTime=!1,i=0;i<arr.length;i++)if("h"!==(c=arr[i].toLowerCase())&&"m"!==c&&"s"!==c&&"a"!==c&&"z"!==c){if("d"!==c&&"m"!==c&&"y"!==c&&"w"!==c&&"e"!==c&&"n"!==c&&"g"!==c){this.badTime=!0;break}}else timeComps.add(c);this.badTime||(comps=timeComps.asArray().sort(function(left,right){return left<right?-1:right<left?1:0}),this.timeComponents=comps.join(""))}!options.clock||"12"!==options.clock&&"24"!==options.clock||(this.clock=options.clock),options.template&&(this.type="",this.length="",this.dateComponents="",this.timeComponents="",this.template=options.template),options.timezone&&(options.timezone instanceof TimeZone?(this.tz=options.timezone,this.timezone=this.tz.getId()):this.timezone=options.timezone),"boolean"==typeof options.useNative&&(this.useNative=options.useNative),void 0===options.meridiems||"chinese"!==options.meridiems&&"gregorian"!==options.meridiems&&"ethiopic"!==options.meridiems||(this.meridiems=options.meridiems),void 0!==options.sync&&(sync=!0===options.sync),void 0!==options.useIntl&&(this.useIntl=options.useIntl),loadParams=options.loadParams,new LocaleInfo(this.locale,{sync:sync,loadParams:loadParams,onLoad:ilib.bind(this,function(li){var len;this.locinfo=li,this.calName=this.calName||this.locinfo.getCalendar()||"gregorian",this.useIntl&&"undefined"!=typeof Intl&&void 0!==Intl.DateTimeFormat&&void 0!==Intl.DateTimeFormat.supportedLocalesOf&&0<Intl.DateTimeFormat.supportedLocalesOf(this.locale.getSpec()).length&&"western"===this.locinfo.getDigitsStyle()&&!options.template&&"gregorian"===this.calName&&(len=DateFmt.lenmap[this.length],"date"===this.type&&("dmy"===this.dateComponents&&"full"!==len||"dmwy"===this.dateComponents&&"full"===len)?this.IntlDateTimeObj=new Intl.DateTimeFormat(this.locale.getSpec(),{dateStyle:len}):"time"===this.type&&"ahm"===this.timeComponents||"ahms"===this.timeComponents?this.IntlDateTimeObj=new Intl.DateTimeFormat(this.locale.getSpec(),{timeStyle:{ahm:"short",ahms:"medium"}[this.timeComponents]}):"date"===this.type&&"m"===this.dateComponents&&"full"===len?this.IntlDateTimeObj=new Intl.DateTimeFormat(this.locale.getSpec(),{month:"long"}):"date"===this.type&&"w"===this.dateComponents&&"full"===len?this.IntlDateTimeObj=new Intl.DateTimeFormat(this.locale.getSpec(),{weekday:"long"}):this.useIntl=!1),this.useIntl?"function"==typeof options.onLoad&&options.onLoad(this):(!this.IntlDateTimeObj&&ilib.isDynCode()&&DateFactory._init(this.calName),CalendarFactory({type:this.calName,sync:sync,loadParams:loadParams,onLoad:ilib.bind(this,function(cal){this.cal=cal,this.cal||(this.cal=new GregorianCal),"default"===this.meridiems&&(this.meridiems=li.getMeridiemsStyle()),new ResBundle({locale:this.locale,name:"sysres",sync:sync,loadParams:loadParams,onLoad:ilib.bind(this,function(rb){this.sysres=rb,this.tz?this._init(options):((rb=options.timezone)||options.locale||(rb="local"),new TimeZone({locale:this.locale,id:rb,sync:sync,loadParams:loadParams,onLoad:ilib.bind(this,function(tz){this.tz=tz,this._init(options)})}))})})})}))})})};DateFmt.lenmap={s:"short",m:"medium",l:"long",f:"full"},DateFmt.defaultFmt={gregorian:{order:"{date} {time}",date:{dmwy:"EEE d/MM/yyyy",dmy:"d/MM/yyyy",dmw:"EEE d/MM",dm:"d/MM",my:"MM/yyyy",dw:"EEE d",d:"dd",m:"MM",y:"yyyy",n:"NN",w:"EEE"},time:{12:"h:mm:ssa",24:"H:mm:ss"},range:{c00:"{st} - {et}, {sd}/{sm}/{sy}",c01:"{sd}/{sm} {st} - {ed}/{em} {et}, {sy}",c02:"{sd}/{sm} {st} - {ed}/{em} {et}, {sy}",c03:"{sd}/{sm}/{sy} {st} - {ed}/{em}/{ey} {et}",c10:"{sd}-{ed}/{sm}/{sy}",c11:"{sd}/{sm} - {ed}/{em} {sy}",c12:"{sd}/{sm}/{sy} - {ed}/{em}/{ey}",c20:"{sm}/{sy} - {em}/{ey}",c30:"{sy} - {ey}"}},islamic:"gregorian",hebrew:"gregorian",julian:"gregorian",buddhist:"gregorian",persian:"gregorian","persian-algo":"gregorian",han:"gregorian"},DateFmt.monthNameLenMap={short:"N",medium:"NN",long:"MMM",full:"MMMM"},DateFmt.weekDayLenMap={short:"E",medium:"EE",long:"EEE",full:"EEEE"},DateFmt.getMeridiemsRange=function(options){options=options||{sync:!0};var args=JSUtils.merge({},options);return args.onLoad=function(fmt){"function"==typeof options.onLoad&&options.onLoad(fmt.getMeridiemsRange())},new DateFmt(args).getMeridiemsRange()},DateFmt.isIntlDateTimeAvailable=function(locale){return!(!locale||!ilib._global("Intl")||void 0===Intl.DateTimeFormat||void 0===Intl.DateTimeFormat.supportedLocalesOf)&&0<Intl.DateTimeFormat.supportedLocalesOf(locale).length},DateFmt.prototype={_init:function(options){void 0===options.sync&&(options.sync=!0),Utils.loadData({object:"DateFmt",locale:this.locale,name:"dateformats.json",sync:options.sync,loadParams:options.loadParams,callback:ilib.bind(this,function(formats){formats=formats||ilib.data.dateformats||DateFmt.defaultFmt,this.info=formats;var ret=this;if(this.template)this._massageTemplate();else if(void 0===this.clock&&(this.clock=this.locinfo.getClock()),"boolean"!=typeof options.sync||options.sync)this._initTemplate(formats),this._massageTemplate();else try{this._initTemplate(formats),this._massageTemplate()}catch(e){ret=void 0}"function"==typeof options.onLoad&&options.onLoad(ret)})})},_initTemplate:function(formats){if(!formats[this.calName])throw"No formats available for calendar "+this.calName+" in locale "+this.locale.toString();var name=formats[this.calName];switch(this.formats="string"==typeof name?formats[name]:name,this.template="",this.type){case"datetime":this.template=this.formats&&this._getLengthFormat(this.formats.order,this.length)||"{date} {time}",this.template=this.template.replace("{date}",this._getFormat(this.formats.date,this.dateComponents,this.length)||""),this.template=this.template.replace("{time}",this._getFormat(this.formats.time[this.clock],this.timeComponents,this.length)||"");break;case"date":this.template=this._getFormat(this.formats.date,this.dateComponents,this.length);break;case"time":this.template=this._getFormat(this.formats.time[this.clock],this.timeComponents,this.length)}this.componentOrder=this._getFormat(this.formats.date,"dmy","l").replace(/[^dMy]/g,"").replace(/y+/,"y").replace(/d+/,"d").replace(/M+/,"m")},_massageTemplate:function(){var i,digits;if(this.clock&&this.template){var temp="";switch(this.clock){case"24":for(i=0;i<this.template.length;i++)if("'"==this.template.charAt(i)){for(temp+=this.template.charAt(i++);i<this.template.length&&"'"!==this.template.charAt(i);)temp+=this.template.charAt(i++);i<this.template.length&&(temp+=this.template.charAt(i))}else"K"==this.template.charAt(i)?temp+="k":"h"==this.template.charAt(i)?temp+="H":temp+=this.template.charAt(i);this.template=temp;break;case"12":for(i=0;i<this.template.length;i++)if("'"==this.template.charAt(i)){for(temp+=this.template.charAt(i++);i<this.template.length&&"'"!==this.template.charAt(i);)temp+=this.template.charAt(i++);i<this.template.length&&(temp+=this.template.charAt(i))}else"k"==this.template.charAt(i)?temp+="K":"H"==this.template.charAt(i)?temp+="h":temp+=this.template.charAt(i);this.template=temp}}this.templateArr=this._tokenize(this.template),"boolean"==typeof this.useNative?this.useNative&&(digits=this.locinfo.getNativeDigits())&&(this.digits=digits):"native"===this.locinfo.getDigitsStyle()&&(digits=this.locinfo.getNativeDigits())&&(this.useNative=!0,this.digits=digits)},_tokenize:function(template){var start,ch,letter,i=0,arr=[];if(template)for(;i<template.length;){if(start=i,"'"===(ch=template.charAt(i))){for(i++;i<template.length&&"'"!==template.charAt(i);)i++;i<template.length&&i++}else if("a"<=ch&&ch<="z"||"A"<=ch&&ch<="Z")for(letter=template.charAt(i);i<template.length&&ch===letter;)ch=template.charAt(++i);else for(;i<template.length&&"'"!==ch&&(ch<"a"||"z"<ch)&&(ch<"A"||"Z"<ch);)ch=template.charAt(++i);arr.push(template.substring(start,i))}return arr},_getFormatInternal:function getFormatInternal(obj,components,length){if(void 0!==components&&obj&&obj[components])return this._getLengthFormat(obj[components],length)},_standAlones:{m:"l",my:"mys",d:"a",w:"e",y:"r"},_getFormat:function getFormat(obj,components,length){if(components&&this._standAlones[components]){var tmp=this._getFormatInternal(obj,this._standAlones[components],length);if(tmp)return tmp}return this._getFormatInternal(obj,components,length)},_getLengthFormat:function getLengthFormat(obj,length){return"string"==typeof obj?obj:obj[length]||void 0},getLocale:function(){return this.locale},getTemplate:function(){return this.template},getDateComponentOrder:function(){return this.componentOrder},getType:function(){return this.type},getCalendar:function(){return this.cal.getType()||"gregorian"},getLength:function(){return DateFmt.lenmap[this.length]||""},getDateComponents:function(){return this.dateComponents||""},getTimeComponents:function(){return this.timeComponents||""},getTimeZone:function(){return this.tz},getClock:function(){return this.clock||this.locinfo.getClock()},getMeridiemsRange:function(){function _getSysString(key){return(this.sysres.getString(void 0,key+"-"+this.calName)||this.sysres.getString(void 0,key)).toString()}var result;switch(this.meridiems){case"chinese":result=[{name:_getSysString.call(this,"azh0"),start:"00:00",end:"05:59"},{name:_getSysString.call(this,"azh1"),start:"06:00",end:"08:59"},{name:_getSysString.call(this,"azh2"),start:"09:00",end:"11:59"},{name:_getSysString.call(this,"azh3"),start:"12:00",end:"12:59"},{name:_getSysString.call(this,"azh4"),start:"13:00",end:"17:59"},{name:_getSysString.call(this,"azh5"),start:"18:00",end:"20:59"},{name:_getSysString.call(this,"azh6"),start:"21:00",end:"23:59"}];break;case"ethiopic":result=[{name:_getSysString.call(this,"a0-ethiopic"),start:"00:00",end:"05:59"},{name:_getSysString.call(this,"a1-ethiopic"),start:"06:00",end:"06:00"},{name:_getSysString.call(this,"a2-ethiopic"),start:"06:01",end:"11:59"},{name:_getSysString.call(this,"a3-ethiopic"),start:"12:00",end:"17:59"},{name:_getSysString.call(this,"a4-ethiopic"),start:"18:00",end:"23:59"}];break;default:result=[{name:_getSysString.call(this,"a0"),start:"00:00",end:"11:59"},{name:_getSysString.call(this,"a1"),start:"12:00",end:"23:59"}]}return result},_findMeridiem:function(hours,minutes){var range=this.info.dayPeriods;if(!range)return"";for(var minuteOfDay=60*hours+minutes,shortest={name:"",length:2e3},i=0;i<range.length;i++){var periodCode,period=range[i];(minuteOfDay===period.at||minuteOfDay>=period.from&&minuteOfDay<period.to)&&(periodCode="B"+i,(period=void 0!==period.at?0:period.to-period.from)<shortest.length)&&(shortest={name:this.sysres.getString(void 0,periodCode+"-"+this.calName)||this.sysres.getString(void 0,periodCode),length:period})}return shortest.name},_getTemplate:function(prefix,calendar){return"gregorian"!==calendar?prefix+"-"+calendar:prefix},getMonthsOfYear:function(options){for(var length=options&&options.length||this.getLength(),template=DateFmt.monthNameLenMap[length],months=[void 0],date=(date=options&&(options.date&&(date=DateFactory._dateToIlib(options.date)),options.year)?DateFactory({year:options.year,month:1,day:1,type:this.cal.getType()}):date)||DateFactory({calendar:this.cal.getType()}),monthCount=this.cal.getNumMonths(date.getYears()),i=1;i<=monthCount;i++)months[i]=this.sysres.getString(this._getTemplate(template+i,this.cal.getType())).toString();return months},getDaysOfWeek:function(options){for(var options=options&&options.length||this.getLength(),template=DateFmt.weekDayLenMap[options],days=[],i=0;i<7;i++)days[i]=this.sysres.getString(this._getTemplate(template+i,this.cal.getType())).toString();return days},toString:function(){return this.getTemplate()},_formatTemplate:function(date,templateArr){for(var key,temp,str="",i=0;i<templateArr.length;i++)switch(templateArr[i]){case"d":str+=date.day||1;break;case"dd":str+=JSUtils.pad(date.day||"1",2);break;case"yy":temp=""+(date.year||0)%100,str+=JSUtils.pad(temp,2);break;case"yyyy":str+=JSUtils.pad(date.year||"0",4);break;case"M":str+=date.month||1;break;case"MM":str+=JSUtils.pad(date.month||"1",2);break;case"h":str+=temp=0==(temp=(date.hour||0)%12)?"12":temp;break;case"hh":0==(temp=(date.hour||0)%12)&&(temp="12"),str+=JSUtils.pad(temp,2);break;case"K":str+=temp=(date.hour||0)%12;break;case"KK":temp=(date.hour||0)%12,str+=JSUtils.pad(temp,2);break;case"H":str+=date.hour||"0";break;case"HH":str+=JSUtils.pad(date.hour||"0",2);break;case"k":str+=0==date.hour?"24":date.hour;break;case"kk":temp=0==date.hour?"24":date.hour,str+=JSUtils.pad(temp,2);break;case"m":str+=date.minute||"0";break;case"mm":str+=JSUtils.pad(date.minute||"0",2);break;case"s":str+=date.second||"0";break;case"ss":str+=JSUtils.pad(date.second||"0",2);break;case"S":str+=date.millisecond||"0";break;case"SSS":str+=JSUtils.pad(date.millisecond||"0",3);break;case"N":case"NN":case"MMM":case"MMMM":case"L":case"LL":case"LLL":case"LLLL":key=templateArr[i]+(date.month||1),str+=this.sysres.getString(void 0,key+"-"+this.calName)||this.sysres.getString(void 0,key)||this.sysres.getString(void 0,key.replace(/L/g,"M")+"-"+this.calName)||this.sysres.getString(void 0,key.replace(/L/g,"M"));break;case"E":case"EE":case"EEE":case"EEEE":case"c":case"cc":case"ccc":case"cccc":key=templateArr[i]+date.getDayOfWeek(),str+=this.sysres.getString(void 0,key+"-"+this.calName)||this.sysres.getString(void 0,key);break;case"a":switch(this.meridiems){case"chinese":key=date.hour<6?"azh0":date.hour<9?"azh1":date.hour<12?"azh2":date.hour<13?"azh3":date.hour<18?"azh4":date.hour<21?"azh5":"azh6";break;case"ethiopic":date.hour<6?key="a0-ethiopic":6===date.hour&&0===date.minute?key="a1-ethiopic":6<=date.hour&&date.hour<12?key="a2-ethiopic":12<=date.hour&&date.hour<18?key="a3-ethiopic":18<=date.hour&&(key="a4-ethiopic");break;default:key=date.hour<12?"a0":"a1"}str+=this.sysres.getString(void 0,key+"-"+this.calName)||this.sysres.getString(void 0,key);break;case"B":str+=this._findMeridiem(date.hour,date.minute);break;case"w":str+=date.getWeekOfYear();break;case"ww":str+=JSUtils.pad(date.getWeekOfYear(),2);break;case"D":str+=date.getDayOfYear();break;case"DD":str+=JSUtils.pad(date.getDayOfYear(),2);break;case"DDD":str+=JSUtils.pad(date.getDayOfYear(),3);break;case"W":str+=date.getWeekOfMonth(this.locale);break;case"G":key="G"+date.getEra(),str+=this.sysres.getString(void 0,key+"-"+this.calName)||this.sysres.getString(void 0,key);break;case"O":str+=(temp=this.sysres.getString("1#1st|2#2nd|3#3rd|21#21st|22#22nd|23#23rd|31#31st|#{num}th","ordinalChoice")).formatChoice(date.day,{num:date.day},!1);break;case"z":str+=this.getTimeZone().getDisplayName(date,"standard");break;case"Z":str+=this.getTimeZone().getDisplayName(date,"rfc822");break;default:str+=templateArr[i].replace(/'/g,"")}return str=this.digits?JSUtils.mapString(str,this.digits):str},format:function(dateLike){var jsDate,thisZoneName=this.tz&&this.tz.getId()||"local",dateLike=DateFactory._dateToIlib(dateLike,thisZoneName,this.locale);if(dateLike.getCalendar&&dateLike instanceof IDate)return this.useIntl&&this.IntlDateTimeObj?(jsDate=DateFactory._ilibToDate(dateLike,thisZoneName,this.locale),this.IntlDateTimeObj.format(jsDate)):((dateLike.timezone||"local")===thisZoneName&&dateLike.getCalendar()===this.calName||(dateLike=DateFactory({type:this.calName,timezone:thisZoneName,julianday:dateLike.getJulianDay()})),this._formatTemplate(dateLike,this.templateArr));throw"Wrong date type passed to DateFmt.format()"},formatRelative:function(reference,date){var fmt,diff,num;if(reference=DateFactory._dateToIlib(reference),date=DateFactory._dateToIlib(date),"object"!=typeof reference||!reference.getCalendar||reference.getCalendar()!==this.calName||"object"!=typeof date||!date.getCalendar||date.getCalendar()!==this.calName)throw"Wrong calendar type";if(diff=reference.getRataDie()-date.getRataDie(),(reference=Math.abs(diff))<694444e-9)switch(num=Math.round(86400*reference),this.length){case"s":fmt=0<diff?this.sysres.getString("#{num}s ago"):this.sysres.getString("#in {num}s");break;case"m":fmt=0<diff?this.sysres.getString("1#1 sec ago|#{num} sec ago"):this.sysres.getString("1#in 1 sec|#in {num} sec");break;default:case"f":case"l":fmt=0<diff?this.sysres.getString("1#1 second ago|#{num} seconds ago"):this.sysres.getString("1#in 1 second|#in {num} seconds")}else if(reference<.041666667)switch(num=Math.round(1440*reference),this.length){case"s":fmt=0<diff?this.sysres.getString("#{num}mi ago"):this.sysres.getString("#in {num}mi");break;case"m":fmt=0<diff?this.sysres.getString("1#1 min ago|#{num} min ago"):this.sysres.getString("1#in 1 min|#in {num} min");break;default:case"f":case"l":fmt=0<diff?this.sysres.getString("1#1 minute ago|#{num} minutes ago"):this.sysres.getString("1#in 1 minute|#in {num} minutes")}else if(reference<1)switch(num=Math.round(24*reference),this.length){case"s":fmt=0<diff?this.sysres.getString("#{num}h ago"):this.sysres.getString("#in {num}h");break;case"m":fmt=0<diff?this.sysres.getString("1#1 hr ago|#{num} hrs ago"):this.sysres.getString("1#in 1 hr|#in {num} hrs");break;default:case"f":case"l":fmt=0<diff?this.sysres.getString("1#1 hour ago|#{num} hours ago"):this.sysres.getString("1#in 1 hour|#in {num} hours")}else if(reference<14)switch(num=Math.round(reference),this.length){case"s":fmt=0<diff?this.sysres.getString("#{num}d ago"):this.sysres.getString("#in {num}d");break;case"m":fmt=0<diff?this.sysres.getString("1#1 dy ago|#{num} dys ago"):this.sysres.getString("1#in 1 dy|#in {num} dys");break;default:case"f":case"l":fmt=0<diff?this.sysres.getString("1#1 day ago|#{num} days ago"):this.sysres.getString("1#in 1 day|#in {num} days")}else if(reference<84)switch(num=Math.round(reference/7),this.length){case"s":fmt=0<diff?this.sysres.getString("#{num}w ago"):this.sysres.getString("#in {num}w");break;case"m":fmt=0<diff?this.sysres.getString("1#1 wk ago|#{num} wks ago"):this.sysres.getString("1#in 1 wk|#in {num} wks");break;default:case"f":case"l":fmt=0<diff?this.sysres.getString("1#1 week ago|#{num} weeks ago"):this.sysres.getString("1#in 1 week|#in {num} weeks")}else if(reference<730)switch(num=Math.round(reference/30.4),this.length){case"s":fmt=0<diff?this.sysres.getString("#{num}mo ago"):this.sysres.getString("#in {num}mo");break;case"m":fmt=0<diff?this.sysres.getString("1#1 mon ago|#{num} mons ago"):this.sysres.getString("1#in 1 mon|#in {num} mons");break;default:case"f":case"l":fmt=0<diff?this.sysres.getString("1#1 month ago|#{num} months ago"):this.sysres.getString("1#in 1 month|#in {num} months")}else switch(num=Math.round(reference/365),this.length){case"s":fmt=0<diff?this.sysres.getString("#{num}y ago"):this.sysres.getString("#in {num}y");break;case"m":fmt=0<diff?this.sysres.getString("1#1 yr ago|#{num} yrs ago"):this.sysres.getString("1#in 1 yr|#in {num} yrs");break;default:case"f":case"l":fmt=0<diff?this.sysres.getString("1#1 year ago|#{num} years ago"):this.sysres.getString("1#in 1 year|#in {num} years")}return fmt.formatChoice(num,{num:num})}},module.exports=DateFmt;