luxon.js 215 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. // these aren't really private, but nor are they really useful to document
  4. /**
  5. * @private
  6. */
  7. class LuxonError extends Error {}
  8. /**
  9. * @private
  10. */
  11. class InvalidDateTimeError extends LuxonError {
  12. constructor(reason) {
  13. super(`Invalid DateTime: ${reason.toMessage()}`);
  14. }
  15. }
  16. /**
  17. * @private
  18. */
  19. class InvalidIntervalError extends LuxonError {
  20. constructor(reason) {
  21. super(`Invalid Interval: ${reason.toMessage()}`);
  22. }
  23. }
  24. /**
  25. * @private
  26. */
  27. class InvalidDurationError extends LuxonError {
  28. constructor(reason) {
  29. super(`Invalid Duration: ${reason.toMessage()}`);
  30. }
  31. }
  32. /**
  33. * @private
  34. */
  35. class ConflictingSpecificationError extends LuxonError {}
  36. /**
  37. * @private
  38. */
  39. class InvalidUnitError extends LuxonError {
  40. constructor(unit) {
  41. super(`Invalid unit ${unit}`);
  42. }
  43. }
  44. /**
  45. * @private
  46. */
  47. class InvalidArgumentError extends LuxonError {}
  48. /**
  49. * @private
  50. */
  51. class ZoneIsAbstractError extends LuxonError {
  52. constructor() {
  53. super("Zone is an abstract class");
  54. }
  55. }
  56. /**
  57. * @private
  58. */
  59. const n = "numeric",
  60. s = "short",
  61. l = "long";
  62. const DATE_SHORT = {
  63. year: n,
  64. month: n,
  65. day: n
  66. };
  67. const DATE_MED = {
  68. year: n,
  69. month: s,
  70. day: n
  71. };
  72. const DATE_MED_WITH_WEEKDAY = {
  73. year: n,
  74. month: s,
  75. day: n,
  76. weekday: s
  77. };
  78. const DATE_FULL = {
  79. year: n,
  80. month: l,
  81. day: n
  82. };
  83. const DATE_HUGE = {
  84. year: n,
  85. month: l,
  86. day: n,
  87. weekday: l
  88. };
  89. const TIME_SIMPLE = {
  90. hour: n,
  91. minute: n
  92. };
  93. const TIME_WITH_SECONDS = {
  94. hour: n,
  95. minute: n,
  96. second: n
  97. };
  98. const TIME_WITH_SHORT_OFFSET = {
  99. hour: n,
  100. minute: n,
  101. second: n,
  102. timeZoneName: s
  103. };
  104. const TIME_WITH_LONG_OFFSET = {
  105. hour: n,
  106. minute: n,
  107. second: n,
  108. timeZoneName: l
  109. };
  110. const TIME_24_SIMPLE = {
  111. hour: n,
  112. minute: n,
  113. hourCycle: "h23"
  114. };
  115. const TIME_24_WITH_SECONDS = {
  116. hour: n,
  117. minute: n,
  118. second: n,
  119. hourCycle: "h23"
  120. };
  121. const TIME_24_WITH_SHORT_OFFSET = {
  122. hour: n,
  123. minute: n,
  124. second: n,
  125. hourCycle: "h23",
  126. timeZoneName: s
  127. };
  128. const TIME_24_WITH_LONG_OFFSET = {
  129. hour: n,
  130. minute: n,
  131. second: n,
  132. hourCycle: "h23",
  133. timeZoneName: l
  134. };
  135. const DATETIME_SHORT = {
  136. year: n,
  137. month: n,
  138. day: n,
  139. hour: n,
  140. minute: n
  141. };
  142. const DATETIME_SHORT_WITH_SECONDS = {
  143. year: n,
  144. month: n,
  145. day: n,
  146. hour: n,
  147. minute: n,
  148. second: n
  149. };
  150. const DATETIME_MED = {
  151. year: n,
  152. month: s,
  153. day: n,
  154. hour: n,
  155. minute: n
  156. };
  157. const DATETIME_MED_WITH_SECONDS = {
  158. year: n,
  159. month: s,
  160. day: n,
  161. hour: n,
  162. minute: n,
  163. second: n
  164. };
  165. const DATETIME_MED_WITH_WEEKDAY = {
  166. year: n,
  167. month: s,
  168. day: n,
  169. weekday: s,
  170. hour: n,
  171. minute: n
  172. };
  173. const DATETIME_FULL = {
  174. year: n,
  175. month: l,
  176. day: n,
  177. hour: n,
  178. minute: n,
  179. timeZoneName: s
  180. };
  181. const DATETIME_FULL_WITH_SECONDS = {
  182. year: n,
  183. month: l,
  184. day: n,
  185. hour: n,
  186. minute: n,
  187. second: n,
  188. timeZoneName: s
  189. };
  190. const DATETIME_HUGE = {
  191. year: n,
  192. month: l,
  193. day: n,
  194. weekday: l,
  195. hour: n,
  196. minute: n,
  197. timeZoneName: l
  198. };
  199. const DATETIME_HUGE_WITH_SECONDS = {
  200. year: n,
  201. month: l,
  202. day: n,
  203. weekday: l,
  204. hour: n,
  205. minute: n,
  206. second: n,
  207. timeZoneName: l
  208. };
  209. /*
  210. This is just a junk drawer, containing anything used across multiple classes.
  211. Because Luxon is small(ish), this should stay small and we won't worry about splitting
  212. it up into, say, parsingUtil.js and basicUtil.js and so on. But they are divided up by feature area.
  213. */
  214. /**
  215. * @private
  216. */
  217. // TYPES
  218. function isUndefined(o) {
  219. return typeof o === "undefined";
  220. }
  221. function isNumber(o) {
  222. return typeof o === "number";
  223. }
  224. function isInteger(o) {
  225. return typeof o === "number" && o % 1 === 0;
  226. }
  227. function isString(o) {
  228. return typeof o === "string";
  229. }
  230. function isDate(o) {
  231. return Object.prototype.toString.call(o) === "[object Date]";
  232. } // CAPABILITIES
  233. function hasRelative() {
  234. try {
  235. return typeof Intl !== "undefined" && !!Intl.RelativeTimeFormat;
  236. } catch (e) {
  237. return false;
  238. }
  239. } // OBJECTS AND ARRAYS
  240. function maybeArray(thing) {
  241. return Array.isArray(thing) ? thing : [thing];
  242. }
  243. function bestBy(arr, by, compare) {
  244. if (arr.length === 0) {
  245. return undefined;
  246. }
  247. return arr.reduce((best, next) => {
  248. const pair = [by(next), next];
  249. if (!best) {
  250. return pair;
  251. } else if (compare(best[0], pair[0]) === best[0]) {
  252. return best;
  253. } else {
  254. return pair;
  255. }
  256. }, null)[1];
  257. }
  258. function pick(obj, keys) {
  259. return keys.reduce((a, k) => {
  260. a[k] = obj[k];
  261. return a;
  262. }, {});
  263. }
  264. function hasOwnProperty(obj, prop) {
  265. return Object.prototype.hasOwnProperty.call(obj, prop);
  266. } // NUMBERS AND STRINGS
  267. function integerBetween(thing, bottom, top) {
  268. return isInteger(thing) && thing >= bottom && thing <= top;
  269. } // x % n but takes the sign of n instead of x
  270. function floorMod(x, n) {
  271. return x - n * Math.floor(x / n);
  272. }
  273. function padStart(input, n = 2) {
  274. const isNeg = input < 0;
  275. let padded;
  276. if (isNeg) {
  277. padded = "-" + ("" + -input).padStart(n, "0");
  278. } else {
  279. padded = ("" + input).padStart(n, "0");
  280. }
  281. return padded;
  282. }
  283. function parseInteger(string) {
  284. if (isUndefined(string) || string === null || string === "") {
  285. return undefined;
  286. } else {
  287. return parseInt(string, 10);
  288. }
  289. }
  290. function parseFloating(string) {
  291. if (isUndefined(string) || string === null || string === "") {
  292. return undefined;
  293. } else {
  294. return parseFloat(string);
  295. }
  296. }
  297. function parseMillis(fraction) {
  298. // Return undefined (instead of 0) in these cases, where fraction is not set
  299. if (isUndefined(fraction) || fraction === null || fraction === "") {
  300. return undefined;
  301. } else {
  302. const f = parseFloat("0." + fraction) * 1000;
  303. return Math.floor(f);
  304. }
  305. }
  306. function roundTo(number, digits, towardZero = false) {
  307. const factor = 10 ** digits,
  308. rounder = towardZero ? Math.trunc : Math.round;
  309. return rounder(number * factor) / factor;
  310. } // DATE BASICS
  311. function isLeapYear(year) {
  312. return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
  313. }
  314. function daysInYear(year) {
  315. return isLeapYear(year) ? 366 : 365;
  316. }
  317. function daysInMonth(year, month) {
  318. const modMonth = floorMod(month - 1, 12) + 1,
  319. modYear = year + (month - modMonth) / 12;
  320. if (modMonth === 2) {
  321. return isLeapYear(modYear) ? 29 : 28;
  322. } else {
  323. return [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][modMonth - 1];
  324. }
  325. } // covert a calendar object to a local timestamp (epoch, but with the offset baked in)
  326. function objToLocalTS(obj) {
  327. let d = Date.UTC(obj.year, obj.month - 1, obj.day, obj.hour, obj.minute, obj.second, obj.millisecond); // for legacy reasons, years between 0 and 99 are interpreted as 19XX; revert that
  328. if (obj.year < 100 && obj.year >= 0) {
  329. d = new Date(d);
  330. d.setUTCFullYear(d.getUTCFullYear() - 1900);
  331. }
  332. return +d;
  333. }
  334. function weeksInWeekYear(weekYear) {
  335. const p1 = (weekYear + Math.floor(weekYear / 4) - Math.floor(weekYear / 100) + Math.floor(weekYear / 400)) % 7,
  336. last = weekYear - 1,
  337. p2 = (last + Math.floor(last / 4) - Math.floor(last / 100) + Math.floor(last / 400)) % 7;
  338. return p1 === 4 || p2 === 3 ? 53 : 52;
  339. }
  340. function untruncateYear(year) {
  341. if (year > 99) {
  342. return year;
  343. } else return year > 60 ? 1900 + year : 2000 + year;
  344. } // PARSING
  345. function parseZoneInfo(ts, offsetFormat, locale, timeZone = null) {
  346. const date = new Date(ts),
  347. intlOpts = {
  348. hourCycle: "h23",
  349. year: "numeric",
  350. month: "2-digit",
  351. day: "2-digit",
  352. hour: "2-digit",
  353. minute: "2-digit"
  354. };
  355. if (timeZone) {
  356. intlOpts.timeZone = timeZone;
  357. }
  358. const modified = {
  359. timeZoneName: offsetFormat,
  360. ...intlOpts
  361. };
  362. const parsed = new Intl.DateTimeFormat(locale, modified).formatToParts(date).find(m => m.type.toLowerCase() === "timezonename");
  363. return parsed ? parsed.value : null;
  364. } // signedOffset('-5', '30') -> -330
  365. function signedOffset(offHourStr, offMinuteStr) {
  366. let offHour = parseInt(offHourStr, 10); // don't || this because we want to preserve -0
  367. if (Number.isNaN(offHour)) {
  368. offHour = 0;
  369. }
  370. const offMin = parseInt(offMinuteStr, 10) || 0,
  371. offMinSigned = offHour < 0 || Object.is(offHour, -0) ? -offMin : offMin;
  372. return offHour * 60 + offMinSigned;
  373. } // COERCION
  374. function asNumber(value) {
  375. const numericValue = Number(value);
  376. if (typeof value === "boolean" || value === "" || Number.isNaN(numericValue)) throw new InvalidArgumentError(`Invalid unit value ${value}`);
  377. return numericValue;
  378. }
  379. function normalizeObject(obj, normalizer) {
  380. const normalized = {};
  381. for (const u in obj) {
  382. if (hasOwnProperty(obj, u)) {
  383. const v = obj[u];
  384. if (v === undefined || v === null) continue;
  385. normalized[normalizer(u)] = asNumber(v);
  386. }
  387. }
  388. return normalized;
  389. }
  390. function formatOffset(offset, format) {
  391. const hours = Math.trunc(Math.abs(offset / 60)),
  392. minutes = Math.trunc(Math.abs(offset % 60)),
  393. sign = offset >= 0 ? "+" : "-";
  394. switch (format) {
  395. case "short":
  396. return `${sign}${padStart(hours, 2)}:${padStart(minutes, 2)}`;
  397. case "narrow":
  398. return `${sign}${hours}${minutes > 0 ? `:${minutes}` : ""}`;
  399. case "techie":
  400. return `${sign}${padStart(hours, 2)}${padStart(minutes, 2)}`;
  401. default:
  402. throw new RangeError(`Value format ${format} is out of range for property format`);
  403. }
  404. }
  405. function timeObject(obj) {
  406. return pick(obj, ["hour", "minute", "second", "millisecond"]);
  407. }
  408. const ianaRegex = /[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;
  409. /**
  410. * @private
  411. */
  412. const monthsLong = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
  413. const monthsShort = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
  414. const monthsNarrow = ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"];
  415. function months(length) {
  416. switch (length) {
  417. case "narrow":
  418. return [...monthsNarrow];
  419. case "short":
  420. return [...monthsShort];
  421. case "long":
  422. return [...monthsLong];
  423. case "numeric":
  424. return ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"];
  425. case "2-digit":
  426. return ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];
  427. default:
  428. return null;
  429. }
  430. }
  431. const weekdaysLong = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
  432. const weekdaysShort = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
  433. const weekdaysNarrow = ["M", "T", "W", "T", "F", "S", "S"];
  434. function weekdays(length) {
  435. switch (length) {
  436. case "narrow":
  437. return [...weekdaysNarrow];
  438. case "short":
  439. return [...weekdaysShort];
  440. case "long":
  441. return [...weekdaysLong];
  442. case "numeric":
  443. return ["1", "2", "3", "4", "5", "6", "7"];
  444. default:
  445. return null;
  446. }
  447. }
  448. const meridiems = ["AM", "PM"];
  449. const erasLong = ["Before Christ", "Anno Domini"];
  450. const erasShort = ["BC", "AD"];
  451. const erasNarrow = ["B", "A"];
  452. function eras(length) {
  453. switch (length) {
  454. case "narrow":
  455. return [...erasNarrow];
  456. case "short":
  457. return [...erasShort];
  458. case "long":
  459. return [...erasLong];
  460. default:
  461. return null;
  462. }
  463. }
  464. function meridiemForDateTime(dt) {
  465. return meridiems[dt.hour < 12 ? 0 : 1];
  466. }
  467. function weekdayForDateTime(dt, length) {
  468. return weekdays(length)[dt.weekday - 1];
  469. }
  470. function monthForDateTime(dt, length) {
  471. return months(length)[dt.month - 1];
  472. }
  473. function eraForDateTime(dt, length) {
  474. return eras(length)[dt.year < 0 ? 0 : 1];
  475. }
  476. function formatRelativeTime(unit, count, numeric = "always", narrow = false) {
  477. const units = {
  478. years: ["year", "yr."],
  479. quarters: ["quarter", "qtr."],
  480. months: ["month", "mo."],
  481. weeks: ["week", "wk."],
  482. days: ["day", "day", "days"],
  483. hours: ["hour", "hr."],
  484. minutes: ["minute", "min."],
  485. seconds: ["second", "sec."]
  486. };
  487. const lastable = ["hours", "minutes", "seconds"].indexOf(unit) === -1;
  488. if (numeric === "auto" && lastable) {
  489. const isDay = unit === "days";
  490. switch (count) {
  491. case 1:
  492. return isDay ? "tomorrow" : `next ${units[unit][0]}`;
  493. case -1:
  494. return isDay ? "yesterday" : `last ${units[unit][0]}`;
  495. case 0:
  496. return isDay ? "today" : `this ${units[unit][0]}`;
  497. }
  498. }
  499. const isInPast = Object.is(count, -0) || count < 0,
  500. fmtValue = Math.abs(count),
  501. singular = fmtValue === 1,
  502. lilUnits = units[unit],
  503. fmtUnit = narrow ? singular ? lilUnits[1] : lilUnits[2] || lilUnits[1] : singular ? units[unit][0] : unit;
  504. return isInPast ? `${fmtValue} ${fmtUnit} ago` : `in ${fmtValue} ${fmtUnit}`;
  505. }
  506. function stringifyTokens(splits, tokenToString) {
  507. let s = "";
  508. for (const token of splits) {
  509. if (token.literal) {
  510. s += token.val;
  511. } else {
  512. s += tokenToString(token.val);
  513. }
  514. }
  515. return s;
  516. }
  517. const macroTokenToFormatOpts = {
  518. D: DATE_SHORT,
  519. DD: DATE_MED,
  520. DDD: DATE_FULL,
  521. DDDD: DATE_HUGE,
  522. t: TIME_SIMPLE,
  523. tt: TIME_WITH_SECONDS,
  524. ttt: TIME_WITH_SHORT_OFFSET,
  525. tttt: TIME_WITH_LONG_OFFSET,
  526. T: TIME_24_SIMPLE,
  527. TT: TIME_24_WITH_SECONDS,
  528. TTT: TIME_24_WITH_SHORT_OFFSET,
  529. TTTT: TIME_24_WITH_LONG_OFFSET,
  530. f: DATETIME_SHORT,
  531. ff: DATETIME_MED,
  532. fff: DATETIME_FULL,
  533. ffff: DATETIME_HUGE,
  534. F: DATETIME_SHORT_WITH_SECONDS,
  535. FF: DATETIME_MED_WITH_SECONDS,
  536. FFF: DATETIME_FULL_WITH_SECONDS,
  537. FFFF: DATETIME_HUGE_WITH_SECONDS
  538. };
  539. /**
  540. * @private
  541. */
  542. class Formatter {
  543. static create(locale, opts = {}) {
  544. return new Formatter(locale, opts);
  545. }
  546. static parseFormat(fmt) {
  547. let current = null,
  548. currentFull = "",
  549. bracketed = false;
  550. const splits = [];
  551. for (let i = 0; i < fmt.length; i++) {
  552. const c = fmt.charAt(i);
  553. if (c === "'") {
  554. if (currentFull.length > 0) {
  555. splits.push({
  556. literal: bracketed,
  557. val: currentFull
  558. });
  559. }
  560. current = null;
  561. currentFull = "";
  562. bracketed = !bracketed;
  563. } else if (bracketed) {
  564. currentFull += c;
  565. } else if (c === current) {
  566. currentFull += c;
  567. } else {
  568. if (currentFull.length > 0) {
  569. splits.push({
  570. literal: false,
  571. val: currentFull
  572. });
  573. }
  574. currentFull = c;
  575. current = c;
  576. }
  577. }
  578. if (currentFull.length > 0) {
  579. splits.push({
  580. literal: bracketed,
  581. val: currentFull
  582. });
  583. }
  584. return splits;
  585. }
  586. static macroTokenToFormatOpts(token) {
  587. return macroTokenToFormatOpts[token];
  588. }
  589. constructor(locale, formatOpts) {
  590. this.opts = formatOpts;
  591. this.loc = locale;
  592. this.systemLoc = null;
  593. }
  594. formatWithSystemDefault(dt, opts) {
  595. if (this.systemLoc === null) {
  596. this.systemLoc = this.loc.redefaultToSystem();
  597. }
  598. const df = this.systemLoc.dtFormatter(dt, { ...this.opts,
  599. ...opts
  600. });
  601. return df.format();
  602. }
  603. formatDateTime(dt, opts = {}) {
  604. const df = this.loc.dtFormatter(dt, { ...this.opts,
  605. ...opts
  606. });
  607. return df.format();
  608. }
  609. formatDateTimeParts(dt, opts = {}) {
  610. const df = this.loc.dtFormatter(dt, { ...this.opts,
  611. ...opts
  612. });
  613. return df.formatToParts();
  614. }
  615. resolvedOptions(dt, opts = {}) {
  616. const df = this.loc.dtFormatter(dt, { ...this.opts,
  617. ...opts
  618. });
  619. return df.resolvedOptions();
  620. }
  621. num(n, p = 0) {
  622. // we get some perf out of doing this here, annoyingly
  623. if (this.opts.forceSimple) {
  624. return padStart(n, p);
  625. }
  626. const opts = { ...this.opts
  627. };
  628. if (p > 0) {
  629. opts.padTo = p;
  630. }
  631. return this.loc.numberFormatter(opts).format(n);
  632. }
  633. formatDateTimeFromString(dt, fmt) {
  634. const knownEnglish = this.loc.listingMode() === "en",
  635. useDateTimeFormatter = this.loc.outputCalendar && this.loc.outputCalendar !== "gregory",
  636. string = (opts, extract) => this.loc.extract(dt, opts, extract),
  637. formatOffset = opts => {
  638. if (dt.isOffsetFixed && dt.offset === 0 && opts.allowZ) {
  639. return "Z";
  640. }
  641. return dt.isValid ? dt.zone.formatOffset(dt.ts, opts.format) : "";
  642. },
  643. meridiem = () => knownEnglish ? meridiemForDateTime(dt) : string({
  644. hour: "numeric",
  645. hourCycle: "h12"
  646. }, "dayperiod"),
  647. month = (length, standalone) => knownEnglish ? monthForDateTime(dt, length) : string(standalone ? {
  648. month: length
  649. } : {
  650. month: length,
  651. day: "numeric"
  652. }, "month"),
  653. weekday = (length, standalone) => knownEnglish ? weekdayForDateTime(dt, length) : string(standalone ? {
  654. weekday: length
  655. } : {
  656. weekday: length,
  657. month: "long",
  658. day: "numeric"
  659. }, "weekday"),
  660. maybeMacro = token => {
  661. const formatOpts = Formatter.macroTokenToFormatOpts(token);
  662. if (formatOpts) {
  663. return this.formatWithSystemDefault(dt, formatOpts);
  664. } else {
  665. return token;
  666. }
  667. },
  668. era = length => knownEnglish ? eraForDateTime(dt, length) : string({
  669. era: length
  670. }, "era"),
  671. tokenToString = token => {
  672. // Where possible: http://cldr.unicode.org/translation/date-time-1/date-time#TOC-Standalone-vs.-Format-Styles
  673. switch (token) {
  674. // ms
  675. case "S":
  676. return this.num(dt.millisecond);
  677. case "u": // falls through
  678. case "SSS":
  679. return this.num(dt.millisecond, 3);
  680. // seconds
  681. case "s":
  682. return this.num(dt.second);
  683. case "ss":
  684. return this.num(dt.second, 2);
  685. // fractional seconds
  686. case "uu":
  687. return this.num(Math.floor(dt.millisecond / 10), 2);
  688. case "uuu":
  689. return this.num(Math.floor(dt.millisecond / 100));
  690. // minutes
  691. case "m":
  692. return this.num(dt.minute);
  693. case "mm":
  694. return this.num(dt.minute, 2);
  695. // hours
  696. case "h":
  697. return this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12);
  698. case "hh":
  699. return this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12, 2);
  700. case "H":
  701. return this.num(dt.hour);
  702. case "HH":
  703. return this.num(dt.hour, 2);
  704. // offset
  705. case "Z":
  706. // like +6
  707. return formatOffset({
  708. format: "narrow",
  709. allowZ: this.opts.allowZ
  710. });
  711. case "ZZ":
  712. // like +06:00
  713. return formatOffset({
  714. format: "short",
  715. allowZ: this.opts.allowZ
  716. });
  717. case "ZZZ":
  718. // like +0600
  719. return formatOffset({
  720. format: "techie",
  721. allowZ: this.opts.allowZ
  722. });
  723. case "ZZZZ":
  724. // like EST
  725. return dt.zone.offsetName(dt.ts, {
  726. format: "short",
  727. locale: this.loc.locale
  728. });
  729. case "ZZZZZ":
  730. // like Eastern Standard Time
  731. return dt.zone.offsetName(dt.ts, {
  732. format: "long",
  733. locale: this.loc.locale
  734. });
  735. // zone
  736. case "z":
  737. // like America/New_York
  738. return dt.zoneName;
  739. // meridiems
  740. case "a":
  741. return meridiem();
  742. // dates
  743. case "d":
  744. return useDateTimeFormatter ? string({
  745. day: "numeric"
  746. }, "day") : this.num(dt.day);
  747. case "dd":
  748. return useDateTimeFormatter ? string({
  749. day: "2-digit"
  750. }, "day") : this.num(dt.day, 2);
  751. // weekdays - standalone
  752. case "c":
  753. // like 1
  754. return this.num(dt.weekday);
  755. case "ccc":
  756. // like 'Tues'
  757. return weekday("short", true);
  758. case "cccc":
  759. // like 'Tuesday'
  760. return weekday("long", true);
  761. case "ccccc":
  762. // like 'T'
  763. return weekday("narrow", true);
  764. // weekdays - format
  765. case "E":
  766. // like 1
  767. return this.num(dt.weekday);
  768. case "EEE":
  769. // like 'Tues'
  770. return weekday("short", false);
  771. case "EEEE":
  772. // like 'Tuesday'
  773. return weekday("long", false);
  774. case "EEEEE":
  775. // like 'T'
  776. return weekday("narrow", false);
  777. // months - standalone
  778. case "L":
  779. // like 1
  780. return useDateTimeFormatter ? string({
  781. month: "numeric",
  782. day: "numeric"
  783. }, "month") : this.num(dt.month);
  784. case "LL":
  785. // like 01, doesn't seem to work
  786. return useDateTimeFormatter ? string({
  787. month: "2-digit",
  788. day: "numeric"
  789. }, "month") : this.num(dt.month, 2);
  790. case "LLL":
  791. // like Jan
  792. return month("short", true);
  793. case "LLLL":
  794. // like January
  795. return month("long", true);
  796. case "LLLLL":
  797. // like J
  798. return month("narrow", true);
  799. // months - format
  800. case "M":
  801. // like 1
  802. return useDateTimeFormatter ? string({
  803. month: "numeric"
  804. }, "month") : this.num(dt.month);
  805. case "MM":
  806. // like 01
  807. return useDateTimeFormatter ? string({
  808. month: "2-digit"
  809. }, "month") : this.num(dt.month, 2);
  810. case "MMM":
  811. // like Jan
  812. return month("short", false);
  813. case "MMMM":
  814. // like January
  815. return month("long", false);
  816. case "MMMMM":
  817. // like J
  818. return month("narrow", false);
  819. // years
  820. case "y":
  821. // like 2014
  822. return useDateTimeFormatter ? string({
  823. year: "numeric"
  824. }, "year") : this.num(dt.year);
  825. case "yy":
  826. // like 14
  827. return useDateTimeFormatter ? string({
  828. year: "2-digit"
  829. }, "year") : this.num(dt.year.toString().slice(-2), 2);
  830. case "yyyy":
  831. // like 0012
  832. return useDateTimeFormatter ? string({
  833. year: "numeric"
  834. }, "year") : this.num(dt.year, 4);
  835. case "yyyyyy":
  836. // like 000012
  837. return useDateTimeFormatter ? string({
  838. year: "numeric"
  839. }, "year") : this.num(dt.year, 6);
  840. // eras
  841. case "G":
  842. // like AD
  843. return era("short");
  844. case "GG":
  845. // like Anno Domini
  846. return era("long");
  847. case "GGGGG":
  848. return era("narrow");
  849. case "kk":
  850. return this.num(dt.weekYear.toString().slice(-2), 2);
  851. case "kkkk":
  852. return this.num(dt.weekYear, 4);
  853. case "W":
  854. return this.num(dt.weekNumber);
  855. case "WW":
  856. return this.num(dt.weekNumber, 2);
  857. case "o":
  858. return this.num(dt.ordinal);
  859. case "ooo":
  860. return this.num(dt.ordinal, 3);
  861. case "q":
  862. // like 1
  863. return this.num(dt.quarter);
  864. case "qq":
  865. // like 01
  866. return this.num(dt.quarter, 2);
  867. case "X":
  868. return this.num(Math.floor(dt.ts / 1000));
  869. case "x":
  870. return this.num(dt.ts);
  871. default:
  872. return maybeMacro(token);
  873. }
  874. };
  875. return stringifyTokens(Formatter.parseFormat(fmt), tokenToString);
  876. }
  877. formatDurationFromString(dur, fmt) {
  878. const tokenToField = token => {
  879. switch (token[0]) {
  880. case "S":
  881. return "millisecond";
  882. case "s":
  883. return "second";
  884. case "m":
  885. return "minute";
  886. case "h":
  887. return "hour";
  888. case "d":
  889. return "day";
  890. case "w":
  891. return "week";
  892. case "M":
  893. return "month";
  894. case "y":
  895. return "year";
  896. default:
  897. return null;
  898. }
  899. },
  900. tokenToString = lildur => token => {
  901. const mapped = tokenToField(token);
  902. if (mapped) {
  903. return this.num(lildur.get(mapped), token.length);
  904. } else {
  905. return token;
  906. }
  907. },
  908. tokens = Formatter.parseFormat(fmt),
  909. realTokens = tokens.reduce((found, {
  910. literal,
  911. val
  912. }) => literal ? found : found.concat(val), []),
  913. collapsed = dur.shiftTo(...realTokens.map(tokenToField).filter(t => t));
  914. return stringifyTokens(tokens, tokenToString(collapsed));
  915. }
  916. }
  917. class Invalid {
  918. constructor(reason, explanation) {
  919. this.reason = reason;
  920. this.explanation = explanation;
  921. }
  922. toMessage() {
  923. if (this.explanation) {
  924. return `${this.reason}: ${this.explanation}`;
  925. } else {
  926. return this.reason;
  927. }
  928. }
  929. }
  930. /**
  931. * @interface
  932. */
  933. class Zone {
  934. /**
  935. * The type of zone
  936. * @abstract
  937. * @type {string}
  938. */
  939. get type() {
  940. throw new ZoneIsAbstractError();
  941. }
  942. /**
  943. * The name of this zone.
  944. * @abstract
  945. * @type {string}
  946. */
  947. get name() {
  948. throw new ZoneIsAbstractError();
  949. }
  950. get ianaName() {
  951. return this.name;
  952. }
  953. /**
  954. * Returns whether the offset is known to be fixed for the whole year.
  955. * @abstract
  956. * @type {boolean}
  957. */
  958. get isUniversal() {
  959. throw new ZoneIsAbstractError();
  960. }
  961. /**
  962. * Returns the offset's common name (such as EST) at the specified timestamp
  963. * @abstract
  964. * @param {number} ts - Epoch milliseconds for which to get the name
  965. * @param {Object} opts - Options to affect the format
  966. * @param {string} opts.format - What style of offset to return. Accepts 'long' or 'short'.
  967. * @param {string} opts.locale - What locale to return the offset name in.
  968. * @return {string}
  969. */
  970. offsetName(ts, opts) {
  971. throw new ZoneIsAbstractError();
  972. }
  973. /**
  974. * Returns the offset's value as a string
  975. * @abstract
  976. * @param {number} ts - Epoch milliseconds for which to get the offset
  977. * @param {string} format - What style of offset to return.
  978. * Accepts 'narrow', 'short', or 'techie'. Returning '+6', '+06:00', or '+0600' respectively
  979. * @return {string}
  980. */
  981. formatOffset(ts, format) {
  982. throw new ZoneIsAbstractError();
  983. }
  984. /**
  985. * Return the offset in minutes for this zone at the specified timestamp.
  986. * @abstract
  987. * @param {number} ts - Epoch milliseconds for which to compute the offset
  988. * @return {number}
  989. */
  990. offset(ts) {
  991. throw new ZoneIsAbstractError();
  992. }
  993. /**
  994. * Return whether this Zone is equal to another zone
  995. * @abstract
  996. * @param {Zone} otherZone - the zone to compare
  997. * @return {boolean}
  998. */
  999. equals(otherZone) {
  1000. throw new ZoneIsAbstractError();
  1001. }
  1002. /**
  1003. * Return whether this Zone is valid.
  1004. * @abstract
  1005. * @type {boolean}
  1006. */
  1007. get isValid() {
  1008. throw new ZoneIsAbstractError();
  1009. }
  1010. }
  1011. let singleton$1 = null;
  1012. /**
  1013. * Represents the local zone for this JavaScript environment.
  1014. * @implements {Zone}
  1015. */
  1016. class SystemZone extends Zone {
  1017. /**
  1018. * Get a singleton instance of the local zone
  1019. * @return {SystemZone}
  1020. */
  1021. static get instance() {
  1022. if (singleton$1 === null) {
  1023. singleton$1 = new SystemZone();
  1024. }
  1025. return singleton$1;
  1026. }
  1027. /** @override **/
  1028. get type() {
  1029. return "system";
  1030. }
  1031. /** @override **/
  1032. get name() {
  1033. return new Intl.DateTimeFormat().resolvedOptions().timeZone;
  1034. }
  1035. /** @override **/
  1036. get isUniversal() {
  1037. return false;
  1038. }
  1039. /** @override **/
  1040. offsetName(ts, {
  1041. format,
  1042. locale
  1043. }) {
  1044. return parseZoneInfo(ts, format, locale);
  1045. }
  1046. /** @override **/
  1047. formatOffset(ts, format) {
  1048. return formatOffset(this.offset(ts), format);
  1049. }
  1050. /** @override **/
  1051. offset(ts) {
  1052. return -new Date(ts).getTimezoneOffset();
  1053. }
  1054. /** @override **/
  1055. equals(otherZone) {
  1056. return otherZone.type === "system";
  1057. }
  1058. /** @override **/
  1059. get isValid() {
  1060. return true;
  1061. }
  1062. }
  1063. let dtfCache = {};
  1064. function makeDTF(zone) {
  1065. if (!dtfCache[zone]) {
  1066. dtfCache[zone] = new Intl.DateTimeFormat("en-US", {
  1067. hour12: false,
  1068. timeZone: zone,
  1069. year: "numeric",
  1070. month: "2-digit",
  1071. day: "2-digit",
  1072. hour: "2-digit",
  1073. minute: "2-digit",
  1074. second: "2-digit",
  1075. era: "short"
  1076. });
  1077. }
  1078. return dtfCache[zone];
  1079. }
  1080. const typeToPos = {
  1081. year: 0,
  1082. month: 1,
  1083. day: 2,
  1084. era: 3,
  1085. hour: 4,
  1086. minute: 5,
  1087. second: 6
  1088. };
  1089. function hackyOffset(dtf, date) {
  1090. const formatted = dtf.format(date).replace(/\u200E/g, ""),
  1091. parsed = /(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(formatted),
  1092. [, fMonth, fDay, fYear, fadOrBc, fHour, fMinute, fSecond] = parsed;
  1093. return [fYear, fMonth, fDay, fadOrBc, fHour, fMinute, fSecond];
  1094. }
  1095. function partsOffset(dtf, date) {
  1096. const formatted = dtf.formatToParts(date);
  1097. const filled = [];
  1098. for (let i = 0; i < formatted.length; i++) {
  1099. const {
  1100. type,
  1101. value
  1102. } = formatted[i];
  1103. const pos = typeToPos[type];
  1104. if (type === "era") {
  1105. filled[pos] = value;
  1106. } else if (!isUndefined(pos)) {
  1107. filled[pos] = parseInt(value, 10);
  1108. }
  1109. }
  1110. return filled;
  1111. }
  1112. let ianaZoneCache = {};
  1113. /**
  1114. * A zone identified by an IANA identifier, like America/New_York
  1115. * @implements {Zone}
  1116. */
  1117. class IANAZone extends Zone {
  1118. /**
  1119. * @param {string} name - Zone name
  1120. * @return {IANAZone}
  1121. */
  1122. static create(name) {
  1123. if (!ianaZoneCache[name]) {
  1124. ianaZoneCache[name] = new IANAZone(name);
  1125. }
  1126. return ianaZoneCache[name];
  1127. }
  1128. /**
  1129. * Reset local caches. Should only be necessary in testing scenarios.
  1130. * @return {void}
  1131. */
  1132. static resetCache() {
  1133. ianaZoneCache = {};
  1134. dtfCache = {};
  1135. }
  1136. /**
  1137. * Returns whether the provided string is a valid specifier. This only checks the string's format, not that the specifier identifies a known zone; see isValidZone for that.
  1138. * @param {string} s - The string to check validity on
  1139. * @example IANAZone.isValidSpecifier("America/New_York") //=> true
  1140. * @example IANAZone.isValidSpecifier("Sport~~blorp") //=> false
  1141. * @deprecated This method returns false for some valid IANA names. Use isValidZone instead.
  1142. * @return {boolean}
  1143. */
  1144. static isValidSpecifier(s) {
  1145. return this.isValidZone(s);
  1146. }
  1147. /**
  1148. * Returns whether the provided string identifies a real zone
  1149. * @param {string} zone - The string to check
  1150. * @example IANAZone.isValidZone("America/New_York") //=> true
  1151. * @example IANAZone.isValidZone("Fantasia/Castle") //=> false
  1152. * @example IANAZone.isValidZone("Sport~~blorp") //=> false
  1153. * @return {boolean}
  1154. */
  1155. static isValidZone(zone) {
  1156. if (!zone) {
  1157. return false;
  1158. }
  1159. try {
  1160. new Intl.DateTimeFormat("en-US", {
  1161. timeZone: zone
  1162. }).format();
  1163. return true;
  1164. } catch (e) {
  1165. return false;
  1166. }
  1167. }
  1168. constructor(name) {
  1169. super();
  1170. /** @private **/
  1171. this.zoneName = name;
  1172. /** @private **/
  1173. this.valid = IANAZone.isValidZone(name);
  1174. }
  1175. /** @override **/
  1176. get type() {
  1177. return "iana";
  1178. }
  1179. /** @override **/
  1180. get name() {
  1181. return this.zoneName;
  1182. }
  1183. /** @override **/
  1184. get isUniversal() {
  1185. return false;
  1186. }
  1187. /** @override **/
  1188. offsetName(ts, {
  1189. format,
  1190. locale
  1191. }) {
  1192. return parseZoneInfo(ts, format, locale, this.name);
  1193. }
  1194. /** @override **/
  1195. formatOffset(ts, format) {
  1196. return formatOffset(this.offset(ts), format);
  1197. }
  1198. /** @override **/
  1199. offset(ts) {
  1200. const date = new Date(ts);
  1201. if (isNaN(date)) return NaN;
  1202. const dtf = makeDTF(this.name);
  1203. let [year, month, day, adOrBc, hour, minute, second] = dtf.formatToParts ? partsOffset(dtf, date) : hackyOffset(dtf, date);
  1204. if (adOrBc === "BC") {
  1205. year = -Math.abs(year) + 1;
  1206. } // because we're using hour12 and https://bugs.chromium.org/p/chromium/issues/detail?id=1025564&can=2&q=%2224%3A00%22%20datetimeformat
  1207. const adjustedHour = hour === 24 ? 0 : hour;
  1208. const asUTC = objToLocalTS({
  1209. year,
  1210. month,
  1211. day,
  1212. hour: adjustedHour,
  1213. minute,
  1214. second,
  1215. millisecond: 0
  1216. });
  1217. let asTS = +date;
  1218. const over = asTS % 1000;
  1219. asTS -= over >= 0 ? over : 1000 + over;
  1220. return (asUTC - asTS) / (60 * 1000);
  1221. }
  1222. /** @override **/
  1223. equals(otherZone) {
  1224. return otherZone.type === "iana" && otherZone.name === this.name;
  1225. }
  1226. /** @override **/
  1227. get isValid() {
  1228. return this.valid;
  1229. }
  1230. }
  1231. let singleton = null;
  1232. /**
  1233. * A zone with a fixed offset (meaning no DST)
  1234. * @implements {Zone}
  1235. */
  1236. class FixedOffsetZone extends Zone {
  1237. /**
  1238. * Get a singleton instance of UTC
  1239. * @return {FixedOffsetZone}
  1240. */
  1241. static get utcInstance() {
  1242. if (singleton === null) {
  1243. singleton = new FixedOffsetZone(0);
  1244. }
  1245. return singleton;
  1246. }
  1247. /**
  1248. * Get an instance with a specified offset
  1249. * @param {number} offset - The offset in minutes
  1250. * @return {FixedOffsetZone}
  1251. */
  1252. static instance(offset) {
  1253. return offset === 0 ? FixedOffsetZone.utcInstance : new FixedOffsetZone(offset);
  1254. }
  1255. /**
  1256. * Get an instance of FixedOffsetZone from a UTC offset string, like "UTC+6"
  1257. * @param {string} s - The offset string to parse
  1258. * @example FixedOffsetZone.parseSpecifier("UTC+6")
  1259. * @example FixedOffsetZone.parseSpecifier("UTC+06")
  1260. * @example FixedOffsetZone.parseSpecifier("UTC-6:00")
  1261. * @return {FixedOffsetZone}
  1262. */
  1263. static parseSpecifier(s) {
  1264. if (s) {
  1265. const r = s.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);
  1266. if (r) {
  1267. return new FixedOffsetZone(signedOffset(r[1], r[2]));
  1268. }
  1269. }
  1270. return null;
  1271. }
  1272. constructor(offset) {
  1273. super();
  1274. /** @private **/
  1275. this.fixed = offset;
  1276. }
  1277. /** @override **/
  1278. get type() {
  1279. return "fixed";
  1280. }
  1281. /** @override **/
  1282. get name() {
  1283. return this.fixed === 0 ? "UTC" : `UTC${formatOffset(this.fixed, "narrow")}`;
  1284. }
  1285. get ianaName() {
  1286. if (this.fixed === 0) {
  1287. return "Etc/UTC";
  1288. } else {
  1289. return `Etc/GMT${formatOffset(-this.fixed, "narrow")}`;
  1290. }
  1291. }
  1292. /** @override **/
  1293. offsetName() {
  1294. return this.name;
  1295. }
  1296. /** @override **/
  1297. formatOffset(ts, format) {
  1298. return formatOffset(this.fixed, format);
  1299. }
  1300. /** @override **/
  1301. get isUniversal() {
  1302. return true;
  1303. }
  1304. /** @override **/
  1305. offset() {
  1306. return this.fixed;
  1307. }
  1308. /** @override **/
  1309. equals(otherZone) {
  1310. return otherZone.type === "fixed" && otherZone.fixed === this.fixed;
  1311. }
  1312. /** @override **/
  1313. get isValid() {
  1314. return true;
  1315. }
  1316. }
  1317. /**
  1318. * A zone that failed to parse. You should never need to instantiate this.
  1319. * @implements {Zone}
  1320. */
  1321. class InvalidZone extends Zone {
  1322. constructor(zoneName) {
  1323. super();
  1324. /** @private */
  1325. this.zoneName = zoneName;
  1326. }
  1327. /** @override **/
  1328. get type() {
  1329. return "invalid";
  1330. }
  1331. /** @override **/
  1332. get name() {
  1333. return this.zoneName;
  1334. }
  1335. /** @override **/
  1336. get isUniversal() {
  1337. return false;
  1338. }
  1339. /** @override **/
  1340. offsetName() {
  1341. return null;
  1342. }
  1343. /** @override **/
  1344. formatOffset() {
  1345. return "";
  1346. }
  1347. /** @override **/
  1348. offset() {
  1349. return NaN;
  1350. }
  1351. /** @override **/
  1352. equals() {
  1353. return false;
  1354. }
  1355. /** @override **/
  1356. get isValid() {
  1357. return false;
  1358. }
  1359. }
  1360. /**
  1361. * @private
  1362. */
  1363. function normalizeZone(input, defaultZone) {
  1364. if (isUndefined(input) || input === null) {
  1365. return defaultZone;
  1366. } else if (input instanceof Zone) {
  1367. return input;
  1368. } else if (isString(input)) {
  1369. const lowered = input.toLowerCase();
  1370. if (lowered === "default") return defaultZone;else if (lowered === "local" || lowered === "system") return SystemZone.instance;else if (lowered === "utc" || lowered === "gmt") return FixedOffsetZone.utcInstance;else return FixedOffsetZone.parseSpecifier(lowered) || IANAZone.create(input);
  1371. } else if (isNumber(input)) {
  1372. return FixedOffsetZone.instance(input);
  1373. } else if (typeof input === "object" && input.offset && typeof input.offset === "number") {
  1374. // This is dumb, but the instanceof check above doesn't seem to really work
  1375. // so we're duck checking it
  1376. return input;
  1377. } else {
  1378. return new InvalidZone(input);
  1379. }
  1380. }
  1381. let now = () => Date.now(),
  1382. defaultZone = "system",
  1383. defaultLocale = null,
  1384. defaultNumberingSystem = null,
  1385. defaultOutputCalendar = null,
  1386. throwOnInvalid;
  1387. /**
  1388. * Settings contains static getters and setters that control Luxon's overall behavior. Luxon is a simple library with few options, but the ones it does have live here.
  1389. */
  1390. class Settings {
  1391. /**
  1392. * Get the callback for returning the current timestamp.
  1393. * @type {function}
  1394. */
  1395. static get now() {
  1396. return now;
  1397. }
  1398. /**
  1399. * Set the callback for returning the current timestamp.
  1400. * The function should return a number, which will be interpreted as an Epoch millisecond count
  1401. * @type {function}
  1402. * @example Settings.now = () => Date.now() + 3000 // pretend it is 3 seconds in the future
  1403. * @example Settings.now = () => 0 // always pretend it's Jan 1, 1970 at midnight in UTC time
  1404. */
  1405. static set now(n) {
  1406. now = n;
  1407. }
  1408. /**
  1409. * Set the default time zone to create DateTimes in. Does not affect existing instances.
  1410. * Use the value "system" to reset this value to the system's time zone.
  1411. * @type {string}
  1412. */
  1413. static set defaultZone(zone) {
  1414. defaultZone = zone;
  1415. }
  1416. /**
  1417. * Get the default time zone object currently used to create DateTimes. Does not affect existing instances.
  1418. * The default value is the system's time zone (the one set on the machine that runs this code).
  1419. * @type {Zone}
  1420. */
  1421. static get defaultZone() {
  1422. return normalizeZone(defaultZone, SystemZone.instance);
  1423. }
  1424. /**
  1425. * Get the default locale to create DateTimes with. Does not affect existing instances.
  1426. * @type {string}
  1427. */
  1428. static get defaultLocale() {
  1429. return defaultLocale;
  1430. }
  1431. /**
  1432. * Set the default locale to create DateTimes with. Does not affect existing instances.
  1433. * @type {string}
  1434. */
  1435. static set defaultLocale(locale) {
  1436. defaultLocale = locale;
  1437. }
  1438. /**
  1439. * Get the default numbering system to create DateTimes with. Does not affect existing instances.
  1440. * @type {string}
  1441. */
  1442. static get defaultNumberingSystem() {
  1443. return defaultNumberingSystem;
  1444. }
  1445. /**
  1446. * Set the default numbering system to create DateTimes with. Does not affect existing instances.
  1447. * @type {string}
  1448. */
  1449. static set defaultNumberingSystem(numberingSystem) {
  1450. defaultNumberingSystem = numberingSystem;
  1451. }
  1452. /**
  1453. * Get the default output calendar to create DateTimes with. Does not affect existing instances.
  1454. * @type {string}
  1455. */
  1456. static get defaultOutputCalendar() {
  1457. return defaultOutputCalendar;
  1458. }
  1459. /**
  1460. * Set the default output calendar to create DateTimes with. Does not affect existing instances.
  1461. * @type {string}
  1462. */
  1463. static set defaultOutputCalendar(outputCalendar) {
  1464. defaultOutputCalendar = outputCalendar;
  1465. }
  1466. /**
  1467. * Get whether Luxon will throw when it encounters invalid DateTimes, Durations, or Intervals
  1468. * @type {boolean}
  1469. */
  1470. static get throwOnInvalid() {
  1471. return throwOnInvalid;
  1472. }
  1473. /**
  1474. * Set whether Luxon will throw when it encounters invalid DateTimes, Durations, or Intervals
  1475. * @type {boolean}
  1476. */
  1477. static set throwOnInvalid(t) {
  1478. throwOnInvalid = t;
  1479. }
  1480. /**
  1481. * Reset Luxon's global caches. Should only be necessary in testing scenarios.
  1482. * @return {void}
  1483. */
  1484. static resetCaches() {
  1485. Locale.resetCache();
  1486. IANAZone.resetCache();
  1487. }
  1488. }
  1489. let intlLFCache = {};
  1490. function getCachedLF(locString, opts = {}) {
  1491. const key = JSON.stringify([locString, opts]);
  1492. let dtf = intlLFCache[key];
  1493. if (!dtf) {
  1494. dtf = new Intl.ListFormat(locString, opts);
  1495. intlLFCache[key] = dtf;
  1496. }
  1497. return dtf;
  1498. }
  1499. let intlDTCache = {};
  1500. function getCachedDTF(locString, opts = {}) {
  1501. const key = JSON.stringify([locString, opts]);
  1502. let dtf = intlDTCache[key];
  1503. if (!dtf) {
  1504. dtf = new Intl.DateTimeFormat(locString, opts);
  1505. intlDTCache[key] = dtf;
  1506. }
  1507. return dtf;
  1508. }
  1509. let intlNumCache = {};
  1510. function getCachedINF(locString, opts = {}) {
  1511. const key = JSON.stringify([locString, opts]);
  1512. let inf = intlNumCache[key];
  1513. if (!inf) {
  1514. inf = new Intl.NumberFormat(locString, opts);
  1515. intlNumCache[key] = inf;
  1516. }
  1517. return inf;
  1518. }
  1519. let intlRelCache = {};
  1520. function getCachedRTF(locString, opts = {}) {
  1521. const {
  1522. base,
  1523. ...cacheKeyOpts
  1524. } = opts; // exclude `base` from the options
  1525. const key = JSON.stringify([locString, cacheKeyOpts]);
  1526. let inf = intlRelCache[key];
  1527. if (!inf) {
  1528. inf = new Intl.RelativeTimeFormat(locString, opts);
  1529. intlRelCache[key] = inf;
  1530. }
  1531. return inf;
  1532. }
  1533. let sysLocaleCache = null;
  1534. function systemLocale() {
  1535. if (sysLocaleCache) {
  1536. return sysLocaleCache;
  1537. } else {
  1538. sysLocaleCache = new Intl.DateTimeFormat().resolvedOptions().locale;
  1539. return sysLocaleCache;
  1540. }
  1541. }
  1542. function parseLocaleString(localeStr) {
  1543. // I really want to avoid writing a BCP 47 parser
  1544. // see, e.g. https://github.com/wooorm/bcp-47
  1545. // Instead, we'll do this:
  1546. // a) if the string has no -u extensions, just leave it alone
  1547. // b) if it does, use Intl to resolve everything
  1548. // c) if Intl fails, try again without the -u
  1549. const uIndex = localeStr.indexOf("-u-");
  1550. if (uIndex === -1) {
  1551. return [localeStr];
  1552. } else {
  1553. let options;
  1554. const smaller = localeStr.substring(0, uIndex);
  1555. try {
  1556. options = getCachedDTF(localeStr).resolvedOptions();
  1557. } catch (e) {
  1558. options = getCachedDTF(smaller).resolvedOptions();
  1559. }
  1560. const {
  1561. numberingSystem,
  1562. calendar
  1563. } = options; // return the smaller one so that we can append the calendar and numbering overrides to it
  1564. return [smaller, numberingSystem, calendar];
  1565. }
  1566. }
  1567. function intlConfigString(localeStr, numberingSystem, outputCalendar) {
  1568. if (outputCalendar || numberingSystem) {
  1569. localeStr += "-u";
  1570. if (outputCalendar) {
  1571. localeStr += `-ca-${outputCalendar}`;
  1572. }
  1573. if (numberingSystem) {
  1574. localeStr += `-nu-${numberingSystem}`;
  1575. }
  1576. return localeStr;
  1577. } else {
  1578. return localeStr;
  1579. }
  1580. }
  1581. function mapMonths(f) {
  1582. const ms = [];
  1583. for (let i = 1; i <= 12; i++) {
  1584. const dt = DateTime.utc(2016, i, 1);
  1585. ms.push(f(dt));
  1586. }
  1587. return ms;
  1588. }
  1589. function mapWeekdays(f) {
  1590. const ms = [];
  1591. for (let i = 1; i <= 7; i++) {
  1592. const dt = DateTime.utc(2016, 11, 13 + i);
  1593. ms.push(f(dt));
  1594. }
  1595. return ms;
  1596. }
  1597. function listStuff(loc, length, defaultOK, englishFn, intlFn) {
  1598. const mode = loc.listingMode(defaultOK);
  1599. if (mode === "error") {
  1600. return null;
  1601. } else if (mode === "en") {
  1602. return englishFn(length);
  1603. } else {
  1604. return intlFn(length);
  1605. }
  1606. }
  1607. function supportsFastNumbers(loc) {
  1608. if (loc.numberingSystem && loc.numberingSystem !== "latn") {
  1609. return false;
  1610. } else {
  1611. return loc.numberingSystem === "latn" || !loc.locale || loc.locale.startsWith("en") || new Intl.DateTimeFormat(loc.intl).resolvedOptions().numberingSystem === "latn";
  1612. }
  1613. }
  1614. /**
  1615. * @private
  1616. */
  1617. class PolyNumberFormatter {
  1618. constructor(intl, forceSimple, opts) {
  1619. this.padTo = opts.padTo || 0;
  1620. this.floor = opts.floor || false;
  1621. const {
  1622. padTo,
  1623. floor,
  1624. ...otherOpts
  1625. } = opts;
  1626. if (!forceSimple || Object.keys(otherOpts).length > 0) {
  1627. const intlOpts = {
  1628. useGrouping: false,
  1629. ...opts
  1630. };
  1631. if (opts.padTo > 0) intlOpts.minimumIntegerDigits = opts.padTo;
  1632. this.inf = getCachedINF(intl, intlOpts);
  1633. }
  1634. }
  1635. format(i) {
  1636. if (this.inf) {
  1637. const fixed = this.floor ? Math.floor(i) : i;
  1638. return this.inf.format(fixed);
  1639. } else {
  1640. // to match the browser's numberformatter defaults
  1641. const fixed = this.floor ? Math.floor(i) : roundTo(i, 3);
  1642. return padStart(fixed, this.padTo);
  1643. }
  1644. }
  1645. }
  1646. /**
  1647. * @private
  1648. */
  1649. class PolyDateFormatter {
  1650. constructor(dt, intl, opts) {
  1651. this.opts = opts;
  1652. let z;
  1653. if (dt.zone.isUniversal) {
  1654. // UTC-8 or Etc/UTC-8 are not part of tzdata, only Etc/GMT+8 and the like.
  1655. // That is why fixed-offset TZ is set to that unless it is:
  1656. // 1. Representing offset 0 when UTC is used to maintain previous behavior and does not become GMT.
  1657. // 2. Unsupported by the browser:
  1658. // - some do not support Etc/
  1659. // - < Etc/GMT-14, > Etc/GMT+12, and 30-minute or 45-minute offsets are not part of tzdata
  1660. const gmtOffset = -1 * (dt.offset / 60);
  1661. const offsetZ = gmtOffset >= 0 ? `Etc/GMT+${gmtOffset}` : `Etc/GMT${gmtOffset}`;
  1662. if (dt.offset !== 0 && IANAZone.create(offsetZ).valid) {
  1663. z = offsetZ;
  1664. this.dt = dt;
  1665. } else {
  1666. // Not all fixed-offset zones like Etc/+4:30 are present in tzdata.
  1667. // So we have to make do. Two cases:
  1668. // 1. The format options tell us to show the zone. We can't do that, so the best
  1669. // we can do is format the date in UTC.
  1670. // 2. The format options don't tell us to show the zone. Then we can adjust them
  1671. // the time and tell the formatter to show it to us in UTC, so that the time is right
  1672. // and the bad zone doesn't show up.
  1673. z = "UTC";
  1674. if (opts.timeZoneName) {
  1675. this.dt = dt;
  1676. } else {
  1677. this.dt = dt.offset === 0 ? dt : DateTime.fromMillis(dt.ts + dt.offset * 60 * 1000);
  1678. }
  1679. }
  1680. } else if (dt.zone.type === "system") {
  1681. this.dt = dt;
  1682. } else {
  1683. this.dt = dt;
  1684. z = dt.zone.name;
  1685. }
  1686. const intlOpts = { ...this.opts
  1687. };
  1688. if (z) {
  1689. intlOpts.timeZone = z;
  1690. }
  1691. this.dtf = getCachedDTF(intl, intlOpts);
  1692. }
  1693. format() {
  1694. return this.dtf.format(this.dt.toJSDate());
  1695. }
  1696. formatToParts() {
  1697. return this.dtf.formatToParts(this.dt.toJSDate());
  1698. }
  1699. resolvedOptions() {
  1700. return this.dtf.resolvedOptions();
  1701. }
  1702. }
  1703. /**
  1704. * @private
  1705. */
  1706. class PolyRelFormatter {
  1707. constructor(intl, isEnglish, opts) {
  1708. this.opts = {
  1709. style: "long",
  1710. ...opts
  1711. };
  1712. if (!isEnglish && hasRelative()) {
  1713. this.rtf = getCachedRTF(intl, opts);
  1714. }
  1715. }
  1716. format(count, unit) {
  1717. if (this.rtf) {
  1718. return this.rtf.format(count, unit);
  1719. } else {
  1720. return formatRelativeTime(unit, count, this.opts.numeric, this.opts.style !== "long");
  1721. }
  1722. }
  1723. formatToParts(count, unit) {
  1724. if (this.rtf) {
  1725. return this.rtf.formatToParts(count, unit);
  1726. } else {
  1727. return [];
  1728. }
  1729. }
  1730. }
  1731. /**
  1732. * @private
  1733. */
  1734. class Locale {
  1735. static fromOpts(opts) {
  1736. return Locale.create(opts.locale, opts.numberingSystem, opts.outputCalendar, opts.defaultToEN);
  1737. }
  1738. static create(locale, numberingSystem, outputCalendar, defaultToEN = false) {
  1739. const specifiedLocale = locale || Settings.defaultLocale; // the system locale is useful for human readable strings but annoying for parsing/formatting known formats
  1740. const localeR = specifiedLocale || (defaultToEN ? "en-US" : systemLocale());
  1741. const numberingSystemR = numberingSystem || Settings.defaultNumberingSystem;
  1742. const outputCalendarR = outputCalendar || Settings.defaultOutputCalendar;
  1743. return new Locale(localeR, numberingSystemR, outputCalendarR, specifiedLocale);
  1744. }
  1745. static resetCache() {
  1746. sysLocaleCache = null;
  1747. intlDTCache = {};
  1748. intlNumCache = {};
  1749. intlRelCache = {};
  1750. }
  1751. static fromObject({
  1752. locale,
  1753. numberingSystem,
  1754. outputCalendar
  1755. } = {}) {
  1756. return Locale.create(locale, numberingSystem, outputCalendar);
  1757. }
  1758. constructor(locale, numbering, outputCalendar, specifiedLocale) {
  1759. const [parsedLocale, parsedNumberingSystem, parsedOutputCalendar] = parseLocaleString(locale);
  1760. this.locale = parsedLocale;
  1761. this.numberingSystem = numbering || parsedNumberingSystem || null;
  1762. this.outputCalendar = outputCalendar || parsedOutputCalendar || null;
  1763. this.intl = intlConfigString(this.locale, this.numberingSystem, this.outputCalendar);
  1764. this.weekdaysCache = {
  1765. format: {},
  1766. standalone: {}
  1767. };
  1768. this.monthsCache = {
  1769. format: {},
  1770. standalone: {}
  1771. };
  1772. this.meridiemCache = null;
  1773. this.eraCache = {};
  1774. this.specifiedLocale = specifiedLocale;
  1775. this.fastNumbersCached = null;
  1776. }
  1777. get fastNumbers() {
  1778. if (this.fastNumbersCached == null) {
  1779. this.fastNumbersCached = supportsFastNumbers(this);
  1780. }
  1781. return this.fastNumbersCached;
  1782. }
  1783. listingMode() {
  1784. const isActuallyEn = this.isEnglish();
  1785. const hasNoWeirdness = (this.numberingSystem === null || this.numberingSystem === "latn") && (this.outputCalendar === null || this.outputCalendar === "gregory");
  1786. return isActuallyEn && hasNoWeirdness ? "en" : "intl";
  1787. }
  1788. clone(alts) {
  1789. if (!alts || Object.getOwnPropertyNames(alts).length === 0) {
  1790. return this;
  1791. } else {
  1792. return Locale.create(alts.locale || this.specifiedLocale, alts.numberingSystem || this.numberingSystem, alts.outputCalendar || this.outputCalendar, alts.defaultToEN || false);
  1793. }
  1794. }
  1795. redefaultToEN(alts = {}) {
  1796. return this.clone({ ...alts,
  1797. defaultToEN: true
  1798. });
  1799. }
  1800. redefaultToSystem(alts = {}) {
  1801. return this.clone({ ...alts,
  1802. defaultToEN: false
  1803. });
  1804. }
  1805. months(length, format = false, defaultOK = true) {
  1806. return listStuff(this, length, defaultOK, months, () => {
  1807. const intl = format ? {
  1808. month: length,
  1809. day: "numeric"
  1810. } : {
  1811. month: length
  1812. },
  1813. formatStr = format ? "format" : "standalone";
  1814. if (!this.monthsCache[formatStr][length]) {
  1815. this.monthsCache[formatStr][length] = mapMonths(dt => this.extract(dt, intl, "month"));
  1816. }
  1817. return this.monthsCache[formatStr][length];
  1818. });
  1819. }
  1820. weekdays(length, format = false, defaultOK = true) {
  1821. return listStuff(this, length, defaultOK, weekdays, () => {
  1822. const intl = format ? {
  1823. weekday: length,
  1824. year: "numeric",
  1825. month: "long",
  1826. day: "numeric"
  1827. } : {
  1828. weekday: length
  1829. },
  1830. formatStr = format ? "format" : "standalone";
  1831. if (!this.weekdaysCache[formatStr][length]) {
  1832. this.weekdaysCache[formatStr][length] = mapWeekdays(dt => this.extract(dt, intl, "weekday"));
  1833. }
  1834. return this.weekdaysCache[formatStr][length];
  1835. });
  1836. }
  1837. meridiems(defaultOK = true) {
  1838. return listStuff(this, undefined, defaultOK, () => meridiems, () => {
  1839. // In theory there could be aribitrary day periods. We're gonna assume there are exactly two
  1840. // for AM and PM. This is probably wrong, but it's makes parsing way easier.
  1841. if (!this.meridiemCache) {
  1842. const intl = {
  1843. hour: "numeric",
  1844. hourCycle: "h12"
  1845. };
  1846. this.meridiemCache = [DateTime.utc(2016, 11, 13, 9), DateTime.utc(2016, 11, 13, 19)].map(dt => this.extract(dt, intl, "dayperiod"));
  1847. }
  1848. return this.meridiemCache;
  1849. });
  1850. }
  1851. eras(length, defaultOK = true) {
  1852. return listStuff(this, length, defaultOK, eras, () => {
  1853. const intl = {
  1854. era: length
  1855. }; // This is problematic. Different calendars are going to define eras totally differently. What I need is the minimum set of dates
  1856. // to definitely enumerate them.
  1857. if (!this.eraCache[length]) {
  1858. this.eraCache[length] = [DateTime.utc(-40, 1, 1), DateTime.utc(2017, 1, 1)].map(dt => this.extract(dt, intl, "era"));
  1859. }
  1860. return this.eraCache[length];
  1861. });
  1862. }
  1863. extract(dt, intlOpts, field) {
  1864. const df = this.dtFormatter(dt, intlOpts),
  1865. results = df.formatToParts(),
  1866. matching = results.find(m => m.type.toLowerCase() === field);
  1867. return matching ? matching.value : null;
  1868. }
  1869. numberFormatter(opts = {}) {
  1870. // this forcesimple option is never used (the only caller short-circuits on it, but it seems safer to leave)
  1871. // (in contrast, the rest of the condition is used heavily)
  1872. return new PolyNumberFormatter(this.intl, opts.forceSimple || this.fastNumbers, opts);
  1873. }
  1874. dtFormatter(dt, intlOpts = {}) {
  1875. return new PolyDateFormatter(dt, this.intl, intlOpts);
  1876. }
  1877. relFormatter(opts = {}) {
  1878. return new PolyRelFormatter(this.intl, this.isEnglish(), opts);
  1879. }
  1880. listFormatter(opts = {}) {
  1881. return getCachedLF(this.intl, opts);
  1882. }
  1883. isEnglish() {
  1884. return this.locale === "en" || this.locale.toLowerCase() === "en-us" || new Intl.DateTimeFormat(this.intl).resolvedOptions().locale.startsWith("en-us");
  1885. }
  1886. equals(other) {
  1887. return this.locale === other.locale && this.numberingSystem === other.numberingSystem && this.outputCalendar === other.outputCalendar;
  1888. }
  1889. }
  1890. /*
  1891. * This file handles parsing for well-specified formats. Here's how it works:
  1892. * Two things go into parsing: a regex to match with and an extractor to take apart the groups in the match.
  1893. * An extractor is just a function that takes a regex match array and returns a { year: ..., month: ... } object
  1894. * parse() does the work of executing the regex and applying the extractor. It takes multiple regex/extractor pairs to try in sequence.
  1895. * Extractors can take a "cursor" representing the offset in the match to look at. This makes it easy to combine extractors.
  1896. * combineExtractors() does the work of combining them, keeping track of the cursor through multiple extractions.
  1897. * Some extractions are super dumb and simpleParse and fromStrings help DRY them.
  1898. */
  1899. function combineRegexes(...regexes) {
  1900. const full = regexes.reduce((f, r) => f + r.source, "");
  1901. return RegExp(`^${full}$`);
  1902. }
  1903. function combineExtractors(...extractors) {
  1904. return m => extractors.reduce(([mergedVals, mergedZone, cursor], ex) => {
  1905. const [val, zone, next] = ex(m, cursor);
  1906. return [{ ...mergedVals,
  1907. ...val
  1908. }, zone || mergedZone, next];
  1909. }, [{}, null, 1]).slice(0, 2);
  1910. }
  1911. function parse(s, ...patterns) {
  1912. if (s == null) {
  1913. return [null, null];
  1914. }
  1915. for (const [regex, extractor] of patterns) {
  1916. const m = regex.exec(s);
  1917. if (m) {
  1918. return extractor(m);
  1919. }
  1920. }
  1921. return [null, null];
  1922. }
  1923. function simpleParse(...keys) {
  1924. return (match, cursor) => {
  1925. const ret = {};
  1926. let i;
  1927. for (i = 0; i < keys.length; i++) {
  1928. ret[keys[i]] = parseInteger(match[cursor + i]);
  1929. }
  1930. return [ret, null, cursor + i];
  1931. };
  1932. } // ISO and SQL parsing
  1933. const offsetRegex = /(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/;
  1934. const isoExtendedZone = `(?:${offsetRegex.source}?(?:\\[(${ianaRegex.source})\\])?)?`;
  1935. const isoTimeBaseRegex = /(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/;
  1936. const isoTimeRegex = RegExp(`${isoTimeBaseRegex.source}${isoExtendedZone}`);
  1937. const isoTimeExtensionRegex = RegExp(`(?:T${isoTimeRegex.source})?`);
  1938. const isoYmdRegex = /([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/;
  1939. const isoWeekRegex = /(\d{4})-?W(\d\d)(?:-?(\d))?/;
  1940. const isoOrdinalRegex = /(\d{4})-?(\d{3})/;
  1941. const extractISOWeekData = simpleParse("weekYear", "weekNumber", "weekDay");
  1942. const extractISOOrdinalData = simpleParse("year", "ordinal");
  1943. const sqlYmdRegex = /(\d{4})-(\d\d)-(\d\d)/; // dumbed-down version of the ISO one
  1944. const sqlTimeRegex = RegExp(`${isoTimeBaseRegex.source} ?(?:${offsetRegex.source}|(${ianaRegex.source}))?`);
  1945. const sqlTimeExtensionRegex = RegExp(`(?: ${sqlTimeRegex.source})?`);
  1946. function int(match, pos, fallback) {
  1947. const m = match[pos];
  1948. return isUndefined(m) ? fallback : parseInteger(m);
  1949. }
  1950. function extractISOYmd(match, cursor) {
  1951. const item = {
  1952. year: int(match, cursor),
  1953. month: int(match, cursor + 1, 1),
  1954. day: int(match, cursor + 2, 1)
  1955. };
  1956. return [item, null, cursor + 3];
  1957. }
  1958. function extractISOTime(match, cursor) {
  1959. const item = {
  1960. hours: int(match, cursor, 0),
  1961. minutes: int(match, cursor + 1, 0),
  1962. seconds: int(match, cursor + 2, 0),
  1963. milliseconds: parseMillis(match[cursor + 3])
  1964. };
  1965. return [item, null, cursor + 4];
  1966. }
  1967. function extractISOOffset(match, cursor) {
  1968. const local = !match[cursor] && !match[cursor + 1],
  1969. fullOffset = signedOffset(match[cursor + 1], match[cursor + 2]),
  1970. zone = local ? null : FixedOffsetZone.instance(fullOffset);
  1971. return [{}, zone, cursor + 3];
  1972. }
  1973. function extractIANAZone(match, cursor) {
  1974. const zone = match[cursor] ? IANAZone.create(match[cursor]) : null;
  1975. return [{}, zone, cursor + 1];
  1976. } // ISO time parsing
  1977. const isoTimeOnly = RegExp(`^T?${isoTimeBaseRegex.source}$`); // ISO duration parsing
  1978. const isoDuration = /^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/;
  1979. function extractISODuration(match) {
  1980. const [s, yearStr, monthStr, weekStr, dayStr, hourStr, minuteStr, secondStr, millisecondsStr] = match;
  1981. const hasNegativePrefix = s[0] === "-";
  1982. const negativeSeconds = secondStr && secondStr[0] === "-";
  1983. const maybeNegate = (num, force = false) => num !== undefined && (force || num && hasNegativePrefix) ? -num : num;
  1984. return [{
  1985. years: maybeNegate(parseFloating(yearStr)),
  1986. months: maybeNegate(parseFloating(monthStr)),
  1987. weeks: maybeNegate(parseFloating(weekStr)),
  1988. days: maybeNegate(parseFloating(dayStr)),
  1989. hours: maybeNegate(parseFloating(hourStr)),
  1990. minutes: maybeNegate(parseFloating(minuteStr)),
  1991. seconds: maybeNegate(parseFloating(secondStr), secondStr === "-0"),
  1992. milliseconds: maybeNegate(parseMillis(millisecondsStr), negativeSeconds)
  1993. }];
  1994. } // These are a little braindead. EDT *should* tell us that we're in, say, America/New_York
  1995. // and not just that we're in -240 *right now*. But since I don't think these are used that often
  1996. // I'm just going to ignore that
  1997. const obsOffsets = {
  1998. GMT: 0,
  1999. EDT: -4 * 60,
  2000. EST: -5 * 60,
  2001. CDT: -5 * 60,
  2002. CST: -6 * 60,
  2003. MDT: -6 * 60,
  2004. MST: -7 * 60,
  2005. PDT: -7 * 60,
  2006. PST: -8 * 60
  2007. };
  2008. function fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) {
  2009. const result = {
  2010. year: yearStr.length === 2 ? untruncateYear(parseInteger(yearStr)) : parseInteger(yearStr),
  2011. month: monthsShort.indexOf(monthStr) + 1,
  2012. day: parseInteger(dayStr),
  2013. hour: parseInteger(hourStr),
  2014. minute: parseInteger(minuteStr)
  2015. };
  2016. if (secondStr) result.second = parseInteger(secondStr);
  2017. if (weekdayStr) {
  2018. result.weekday = weekdayStr.length > 3 ? weekdaysLong.indexOf(weekdayStr) + 1 : weekdaysShort.indexOf(weekdayStr) + 1;
  2019. }
  2020. return result;
  2021. } // RFC 2822/5322
  2022. const rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/;
  2023. function extractRFC2822(match) {
  2024. const [, weekdayStr, dayStr, monthStr, yearStr, hourStr, minuteStr, secondStr, obsOffset, milOffset, offHourStr, offMinuteStr] = match,
  2025. result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);
  2026. let offset;
  2027. if (obsOffset) {
  2028. offset = obsOffsets[obsOffset];
  2029. } else if (milOffset) {
  2030. offset = 0;
  2031. } else {
  2032. offset = signedOffset(offHourStr, offMinuteStr);
  2033. }
  2034. return [result, new FixedOffsetZone(offset)];
  2035. }
  2036. function preprocessRFC2822(s) {
  2037. // Remove comments and folding whitespace and replace multiple-spaces with a single space
  2038. return s.replace(/\([^)]*\)|[\n\t]/g, " ").replace(/(\s\s+)/g, " ").trim();
  2039. } // http date
  2040. const rfc1123 = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/,
  2041. rfc850 = /^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/,
  2042. ascii = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;
  2043. function extractRFC1123Or850(match) {
  2044. const [, weekdayStr, dayStr, monthStr, yearStr, hourStr, minuteStr, secondStr] = match,
  2045. result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);
  2046. return [result, FixedOffsetZone.utcInstance];
  2047. }
  2048. function extractASCII(match) {
  2049. const [, weekdayStr, monthStr, dayStr, hourStr, minuteStr, secondStr, yearStr] = match,
  2050. result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);
  2051. return [result, FixedOffsetZone.utcInstance];
  2052. }
  2053. const isoYmdWithTimeExtensionRegex = combineRegexes(isoYmdRegex, isoTimeExtensionRegex);
  2054. const isoWeekWithTimeExtensionRegex = combineRegexes(isoWeekRegex, isoTimeExtensionRegex);
  2055. const isoOrdinalWithTimeExtensionRegex = combineRegexes(isoOrdinalRegex, isoTimeExtensionRegex);
  2056. const isoTimeCombinedRegex = combineRegexes(isoTimeRegex);
  2057. const extractISOYmdTimeAndOffset = combineExtractors(extractISOYmd, extractISOTime, extractISOOffset, extractIANAZone);
  2058. const extractISOWeekTimeAndOffset = combineExtractors(extractISOWeekData, extractISOTime, extractISOOffset, extractIANAZone);
  2059. const extractISOOrdinalDateAndTime = combineExtractors(extractISOOrdinalData, extractISOTime, extractISOOffset, extractIANAZone);
  2060. const extractISOTimeAndOffset = combineExtractors(extractISOTime, extractISOOffset, extractIANAZone);
  2061. /*
  2062. * @private
  2063. */
  2064. function parseISODate(s) {
  2065. return parse(s, [isoYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset], [isoWeekWithTimeExtensionRegex, extractISOWeekTimeAndOffset], [isoOrdinalWithTimeExtensionRegex, extractISOOrdinalDateAndTime], [isoTimeCombinedRegex, extractISOTimeAndOffset]);
  2066. }
  2067. function parseRFC2822Date(s) {
  2068. return parse(preprocessRFC2822(s), [rfc2822, extractRFC2822]);
  2069. }
  2070. function parseHTTPDate(s) {
  2071. return parse(s, [rfc1123, extractRFC1123Or850], [rfc850, extractRFC1123Or850], [ascii, extractASCII]);
  2072. }
  2073. function parseISODuration(s) {
  2074. return parse(s, [isoDuration, extractISODuration]);
  2075. }
  2076. const extractISOTimeOnly = combineExtractors(extractISOTime);
  2077. function parseISOTimeOnly(s) {
  2078. return parse(s, [isoTimeOnly, extractISOTimeOnly]);
  2079. }
  2080. const sqlYmdWithTimeExtensionRegex = combineRegexes(sqlYmdRegex, sqlTimeExtensionRegex);
  2081. const sqlTimeCombinedRegex = combineRegexes(sqlTimeRegex);
  2082. const extractISOTimeOffsetAndIANAZone = combineExtractors(extractISOTime, extractISOOffset, extractIANAZone);
  2083. function parseSQL(s) {
  2084. return parse(s, [sqlYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset], [sqlTimeCombinedRegex, extractISOTimeOffsetAndIANAZone]);
  2085. }
  2086. const INVALID$2 = "Invalid Duration"; // unit conversion constants
  2087. const lowOrderMatrix = {
  2088. weeks: {
  2089. days: 7,
  2090. hours: 7 * 24,
  2091. minutes: 7 * 24 * 60,
  2092. seconds: 7 * 24 * 60 * 60,
  2093. milliseconds: 7 * 24 * 60 * 60 * 1000
  2094. },
  2095. days: {
  2096. hours: 24,
  2097. minutes: 24 * 60,
  2098. seconds: 24 * 60 * 60,
  2099. milliseconds: 24 * 60 * 60 * 1000
  2100. },
  2101. hours: {
  2102. minutes: 60,
  2103. seconds: 60 * 60,
  2104. milliseconds: 60 * 60 * 1000
  2105. },
  2106. minutes: {
  2107. seconds: 60,
  2108. milliseconds: 60 * 1000
  2109. },
  2110. seconds: {
  2111. milliseconds: 1000
  2112. }
  2113. },
  2114. casualMatrix = {
  2115. years: {
  2116. quarters: 4,
  2117. months: 12,
  2118. weeks: 52,
  2119. days: 365,
  2120. hours: 365 * 24,
  2121. minutes: 365 * 24 * 60,
  2122. seconds: 365 * 24 * 60 * 60,
  2123. milliseconds: 365 * 24 * 60 * 60 * 1000
  2124. },
  2125. quarters: {
  2126. months: 3,
  2127. weeks: 13,
  2128. days: 91,
  2129. hours: 91 * 24,
  2130. minutes: 91 * 24 * 60,
  2131. seconds: 91 * 24 * 60 * 60,
  2132. milliseconds: 91 * 24 * 60 * 60 * 1000
  2133. },
  2134. months: {
  2135. weeks: 4,
  2136. days: 30,
  2137. hours: 30 * 24,
  2138. minutes: 30 * 24 * 60,
  2139. seconds: 30 * 24 * 60 * 60,
  2140. milliseconds: 30 * 24 * 60 * 60 * 1000
  2141. },
  2142. ...lowOrderMatrix
  2143. },
  2144. daysInYearAccurate = 146097.0 / 400,
  2145. daysInMonthAccurate = 146097.0 / 4800,
  2146. accurateMatrix = {
  2147. years: {
  2148. quarters: 4,
  2149. months: 12,
  2150. weeks: daysInYearAccurate / 7,
  2151. days: daysInYearAccurate,
  2152. hours: daysInYearAccurate * 24,
  2153. minutes: daysInYearAccurate * 24 * 60,
  2154. seconds: daysInYearAccurate * 24 * 60 * 60,
  2155. milliseconds: daysInYearAccurate * 24 * 60 * 60 * 1000
  2156. },
  2157. quarters: {
  2158. months: 3,
  2159. weeks: daysInYearAccurate / 28,
  2160. days: daysInYearAccurate / 4,
  2161. hours: daysInYearAccurate * 24 / 4,
  2162. minutes: daysInYearAccurate * 24 * 60 / 4,
  2163. seconds: daysInYearAccurate * 24 * 60 * 60 / 4,
  2164. milliseconds: daysInYearAccurate * 24 * 60 * 60 * 1000 / 4
  2165. },
  2166. months: {
  2167. weeks: daysInMonthAccurate / 7,
  2168. days: daysInMonthAccurate,
  2169. hours: daysInMonthAccurate * 24,
  2170. minutes: daysInMonthAccurate * 24 * 60,
  2171. seconds: daysInMonthAccurate * 24 * 60 * 60,
  2172. milliseconds: daysInMonthAccurate * 24 * 60 * 60 * 1000
  2173. },
  2174. ...lowOrderMatrix
  2175. }; // units ordered by size
  2176. const orderedUnits$1 = ["years", "quarters", "months", "weeks", "days", "hours", "minutes", "seconds", "milliseconds"];
  2177. const reverseUnits = orderedUnits$1.slice(0).reverse(); // clone really means "create another instance just like this one, but with these changes"
  2178. function clone$1(dur, alts, clear = false) {
  2179. // deep merge for vals
  2180. const conf = {
  2181. values: clear ? alts.values : { ...dur.values,
  2182. ...(alts.values || {})
  2183. },
  2184. loc: dur.loc.clone(alts.loc),
  2185. conversionAccuracy: alts.conversionAccuracy || dur.conversionAccuracy,
  2186. matrix: alts.matrix || dur.matrix
  2187. };
  2188. return new Duration(conf);
  2189. }
  2190. function antiTrunc(n) {
  2191. return n < 0 ? Math.floor(n) : Math.ceil(n);
  2192. } // NB: mutates parameters
  2193. function convert(matrix, fromMap, fromUnit, toMap, toUnit) {
  2194. const conv = matrix[toUnit][fromUnit],
  2195. raw = fromMap[fromUnit] / conv,
  2196. sameSign = Math.sign(raw) === Math.sign(toMap[toUnit]),
  2197. // ok, so this is wild, but see the matrix in the tests
  2198. added = !sameSign && toMap[toUnit] !== 0 && Math.abs(raw) <= 1 ? antiTrunc(raw) : Math.trunc(raw);
  2199. toMap[toUnit] += added;
  2200. fromMap[fromUnit] -= added * conv;
  2201. } // NB: mutates parameters
  2202. function normalizeValues(matrix, vals) {
  2203. reverseUnits.reduce((previous, current) => {
  2204. if (!isUndefined(vals[current])) {
  2205. if (previous) {
  2206. convert(matrix, vals, previous, vals, current);
  2207. }
  2208. return current;
  2209. } else {
  2210. return previous;
  2211. }
  2212. }, null);
  2213. }
  2214. /**
  2215. * A Duration object represents a period of time, like "2 months" or "1 day, 1 hour". Conceptually, it's just a map of units to their quantities, accompanied by some additional configuration and methods for creating, parsing, interrogating, transforming, and formatting them. They can be used on their own or in conjunction with other Luxon types; for example, you can use {@link DateTime#plus} to add a Duration object to a DateTime, producing another DateTime.
  2216. *
  2217. * Here is a brief overview of commonly used methods and getters in Duration:
  2218. *
  2219. * * **Creation** To create a Duration, use {@link Duration.fromMillis}, {@link Duration.fromObject}, or {@link Duration.fromISO}.
  2220. * * **Unit values** See the {@link Duration#years}, {@link Duration#months}, {@link Duration#weeks}, {@link Duration#days}, {@link Duration#hours}, {@link Duration#minutes}, {@link Duration#seconds}, {@link Duration#milliseconds} accessors.
  2221. * * **Configuration** See {@link Duration#locale} and {@link Duration#numberingSystem} accessors.
  2222. * * **Transformation** To create new Durations out of old ones use {@link Duration#plus}, {@link Duration#minus}, {@link Duration#normalize}, {@link Duration#set}, {@link Duration#reconfigure}, {@link Duration#shiftTo}, and {@link Duration#negate}.
  2223. * * **Output** To convert the Duration into other representations, see {@link Duration#as}, {@link Duration#toISO}, {@link Duration#toFormat}, and {@link Duration#toJSON}
  2224. *
  2225. * There's are more methods documented below. In addition, for more information on subtler topics like internationalization and validity, see the external documentation.
  2226. */
  2227. class Duration {
  2228. /**
  2229. * @private
  2230. */
  2231. constructor(config) {
  2232. const accurate = config.conversionAccuracy === "longterm" || false;
  2233. let matrix = accurate ? accurateMatrix : casualMatrix;
  2234. if (config.matrix) {
  2235. matrix = config.matrix;
  2236. }
  2237. /**
  2238. * @access private
  2239. */
  2240. this.values = config.values;
  2241. /**
  2242. * @access private
  2243. */
  2244. this.loc = config.loc || Locale.create();
  2245. /**
  2246. * @access private
  2247. */
  2248. this.conversionAccuracy = accurate ? "longterm" : "casual";
  2249. /**
  2250. * @access private
  2251. */
  2252. this.invalid = config.invalid || null;
  2253. /**
  2254. * @access private
  2255. */
  2256. this.matrix = matrix;
  2257. /**
  2258. * @access private
  2259. */
  2260. this.isLuxonDuration = true;
  2261. }
  2262. /**
  2263. * Create Duration from a number of milliseconds.
  2264. * @param {number} count of milliseconds
  2265. * @param {Object} opts - options for parsing
  2266. * @param {string} [opts.locale='en-US'] - the locale to use
  2267. * @param {string} opts.numberingSystem - the numbering system to use
  2268. * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
  2269. * @return {Duration}
  2270. */
  2271. static fromMillis(count, opts) {
  2272. return Duration.fromObject({
  2273. milliseconds: count
  2274. }, opts);
  2275. }
  2276. /**
  2277. * Create a Duration from a JavaScript object with keys like 'years' and 'hours'.
  2278. * If this object is empty then a zero milliseconds duration is returned.
  2279. * @param {Object} obj - the object to create the DateTime from
  2280. * @param {number} obj.years
  2281. * @param {number} obj.quarters
  2282. * @param {number} obj.months
  2283. * @param {number} obj.weeks
  2284. * @param {number} obj.days
  2285. * @param {number} obj.hours
  2286. * @param {number} obj.minutes
  2287. * @param {number} obj.seconds
  2288. * @param {number} obj.milliseconds
  2289. * @param {Object} [opts=[]] - options for creating this Duration
  2290. * @param {string} [opts.locale='en-US'] - the locale to use
  2291. * @param {string} opts.numberingSystem - the numbering system to use
  2292. * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use
  2293. * @param {string} [opts.matrix=Object] - the custom conversion system to use
  2294. * @return {Duration}
  2295. */
  2296. static fromObject(obj, opts = {}) {
  2297. if (obj == null || typeof obj !== "object") {
  2298. throw new InvalidArgumentError(`Duration.fromObject: argument expected to be an object, got ${obj === null ? "null" : typeof obj}`);
  2299. }
  2300. return new Duration({
  2301. values: normalizeObject(obj, Duration.normalizeUnit),
  2302. loc: Locale.fromObject(opts),
  2303. conversionAccuracy: opts.conversionAccuracy,
  2304. matrix: opts.matrix
  2305. });
  2306. }
  2307. /**
  2308. * Create a Duration from DurationLike.
  2309. *
  2310. * @param {Object | number | Duration} durationLike
  2311. * One of:
  2312. * - object with keys like 'years' and 'hours'.
  2313. * - number representing milliseconds
  2314. * - Duration instance
  2315. * @return {Duration}
  2316. */
  2317. static fromDurationLike(durationLike) {
  2318. if (isNumber(durationLike)) {
  2319. return Duration.fromMillis(durationLike);
  2320. } else if (Duration.isDuration(durationLike)) {
  2321. return durationLike;
  2322. } else if (typeof durationLike === "object") {
  2323. return Duration.fromObject(durationLike);
  2324. } else {
  2325. throw new InvalidArgumentError(`Unknown duration argument ${durationLike} of type ${typeof durationLike}`);
  2326. }
  2327. }
  2328. /**
  2329. * Create a Duration from an ISO 8601 duration string.
  2330. * @param {string} text - text to parse
  2331. * @param {Object} opts - options for parsing
  2332. * @param {string} [opts.locale='en-US'] - the locale to use
  2333. * @param {string} opts.numberingSystem - the numbering system to use
  2334. * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use
  2335. * @param {string} [opts.matrix=Object] - the preset conversion system to use
  2336. * @see https://en.wikipedia.org/wiki/ISO_8601#Durations
  2337. * @example Duration.fromISO('P3Y6M1W4DT12H30M5S').toObject() //=> { years: 3, months: 6, weeks: 1, days: 4, hours: 12, minutes: 30, seconds: 5 }
  2338. * @example Duration.fromISO('PT23H').toObject() //=> { hours: 23 }
  2339. * @example Duration.fromISO('P5Y3M').toObject() //=> { years: 5, months: 3 }
  2340. * @return {Duration}
  2341. */
  2342. static fromISO(text, opts) {
  2343. const [parsed] = parseISODuration(text);
  2344. if (parsed) {
  2345. return Duration.fromObject(parsed, opts);
  2346. } else {
  2347. return Duration.invalid("unparsable", `the input "${text}" can't be parsed as ISO 8601`);
  2348. }
  2349. }
  2350. /**
  2351. * Create a Duration from an ISO 8601 time string.
  2352. * @param {string} text - text to parse
  2353. * @param {Object} opts - options for parsing
  2354. * @param {string} [opts.locale='en-US'] - the locale to use
  2355. * @param {string} opts.numberingSystem - the numbering system to use
  2356. * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use
  2357. * @param {string} [opts.matrix=Object] - the conversion system to use
  2358. * @see https://en.wikipedia.org/wiki/ISO_8601#Times
  2359. * @example Duration.fromISOTime('11:22:33.444').toObject() //=> { hours: 11, minutes: 22, seconds: 33, milliseconds: 444 }
  2360. * @example Duration.fromISOTime('11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }
  2361. * @example Duration.fromISOTime('T11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }
  2362. * @example Duration.fromISOTime('1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }
  2363. * @example Duration.fromISOTime('T1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }
  2364. * @return {Duration}
  2365. */
  2366. static fromISOTime(text, opts) {
  2367. const [parsed] = parseISOTimeOnly(text);
  2368. if (parsed) {
  2369. return Duration.fromObject(parsed, opts);
  2370. } else {
  2371. return Duration.invalid("unparsable", `the input "${text}" can't be parsed as ISO 8601`);
  2372. }
  2373. }
  2374. /**
  2375. * Create an invalid Duration.
  2376. * @param {string} reason - simple string of why this datetime is invalid. Should not contain parameters or anything else data-dependent
  2377. * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information
  2378. * @return {Duration}
  2379. */
  2380. static invalid(reason, explanation = null) {
  2381. if (!reason) {
  2382. throw new InvalidArgumentError("need to specify a reason the Duration is invalid");
  2383. }
  2384. const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
  2385. if (Settings.throwOnInvalid) {
  2386. throw new InvalidDurationError(invalid);
  2387. } else {
  2388. return new Duration({
  2389. invalid
  2390. });
  2391. }
  2392. }
  2393. /**
  2394. * @private
  2395. */
  2396. static normalizeUnit(unit) {
  2397. const normalized = {
  2398. year: "years",
  2399. years: "years",
  2400. quarter: "quarters",
  2401. quarters: "quarters",
  2402. month: "months",
  2403. months: "months",
  2404. week: "weeks",
  2405. weeks: "weeks",
  2406. day: "days",
  2407. days: "days",
  2408. hour: "hours",
  2409. hours: "hours",
  2410. minute: "minutes",
  2411. minutes: "minutes",
  2412. second: "seconds",
  2413. seconds: "seconds",
  2414. millisecond: "milliseconds",
  2415. milliseconds: "milliseconds"
  2416. }[unit ? unit.toLowerCase() : unit];
  2417. if (!normalized) throw new InvalidUnitError(unit);
  2418. return normalized;
  2419. }
  2420. /**
  2421. * Check if an object is a Duration. Works across context boundaries
  2422. * @param {object} o
  2423. * @return {boolean}
  2424. */
  2425. static isDuration(o) {
  2426. return o && o.isLuxonDuration || false;
  2427. }
  2428. /**
  2429. * Get the locale of a Duration, such 'en-GB'
  2430. * @type {string}
  2431. */
  2432. get locale() {
  2433. return this.isValid ? this.loc.locale : null;
  2434. }
  2435. /**
  2436. * Get the numbering system of a Duration, such 'beng'. The numbering system is used when formatting the Duration
  2437. *
  2438. * @type {string}
  2439. */
  2440. get numberingSystem() {
  2441. return this.isValid ? this.loc.numberingSystem : null;
  2442. }
  2443. /**
  2444. * Returns a string representation of this Duration formatted according to the specified format string. You may use these tokens:
  2445. * * `S` for milliseconds
  2446. * * `s` for seconds
  2447. * * `m` for minutes
  2448. * * `h` for hours
  2449. * * `d` for days
  2450. * * `w` for weeks
  2451. * * `M` for months
  2452. * * `y` for years
  2453. * Notes:
  2454. * * Add padding by repeating the token, e.g. "yy" pads the years to two digits, "hhhh" pads the hours out to four digits
  2455. * * Tokens can be escaped by wrapping with single quotes.
  2456. * * The duration will be converted to the set of units in the format string using {@link Duration#shiftTo} and the Durations's conversion accuracy setting.
  2457. * @param {string} fmt - the format string
  2458. * @param {Object} opts - options
  2459. * @param {boolean} [opts.floor=true] - floor numerical values
  2460. * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("y d s") //=> "1 6 2"
  2461. * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("yy dd sss") //=> "01 06 002"
  2462. * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("M S") //=> "12 518402000"
  2463. * @return {string}
  2464. */
  2465. toFormat(fmt, opts = {}) {
  2466. // reverse-compat since 1.2; we always round down now, never up, and we do it by default
  2467. const fmtOpts = { ...opts,
  2468. floor: opts.round !== false && opts.floor !== false
  2469. };
  2470. return this.isValid ? Formatter.create(this.loc, fmtOpts).formatDurationFromString(this, fmt) : INVALID$2;
  2471. }
  2472. /**
  2473. * Returns a string representation of a Duration with all units included.
  2474. * To modify its behavior use the `listStyle` and any Intl.NumberFormat option, though `unitDisplay` is especially relevant.
  2475. * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat
  2476. * @param opts - On option object to override the formatting. Accepts the same keys as the options parameter of the native `Int.NumberFormat` constructor, as well as `listStyle`.
  2477. * @example
  2478. * ```js
  2479. * var dur = Duration.fromObject({ days: 1, hours: 5, minutes: 6 })
  2480. * dur.toHuman() //=> '1 day, 5 hours, 6 minutes'
  2481. * dur.toHuman({ listStyle: "long" }) //=> '1 day, 5 hours, and 6 minutes'
  2482. * dur.toHuman({ unitDisplay: "short" }) //=> '1 day, 5 hr, 6 min'
  2483. * ```
  2484. */
  2485. toHuman(opts = {}) {
  2486. const l = orderedUnits$1.map(unit => {
  2487. const val = this.values[unit];
  2488. if (isUndefined(val)) {
  2489. return null;
  2490. }
  2491. return this.loc.numberFormatter({
  2492. style: "unit",
  2493. unitDisplay: "long",
  2494. ...opts,
  2495. unit: unit.slice(0, -1)
  2496. }).format(val);
  2497. }).filter(n => n);
  2498. return this.loc.listFormatter({
  2499. type: "conjunction",
  2500. style: opts.listStyle || "narrow",
  2501. ...opts
  2502. }).format(l);
  2503. }
  2504. /**
  2505. * Returns a JavaScript object with this Duration's values.
  2506. * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toObject() //=> { years: 1, days: 6, seconds: 2 }
  2507. * @return {Object}
  2508. */
  2509. toObject() {
  2510. if (!this.isValid) return {};
  2511. return { ...this.values
  2512. };
  2513. }
  2514. /**
  2515. * Returns an ISO 8601-compliant string representation of this Duration.
  2516. * @see https://en.wikipedia.org/wiki/ISO_8601#Durations
  2517. * @example Duration.fromObject({ years: 3, seconds: 45 }).toISO() //=> 'P3YT45S'
  2518. * @example Duration.fromObject({ months: 4, seconds: 45 }).toISO() //=> 'P4MT45S'
  2519. * @example Duration.fromObject({ months: 5 }).toISO() //=> 'P5M'
  2520. * @example Duration.fromObject({ minutes: 5 }).toISO() //=> 'PT5M'
  2521. * @example Duration.fromObject({ milliseconds: 6 }).toISO() //=> 'PT0.006S'
  2522. * @return {string}
  2523. */
  2524. toISO() {
  2525. // we could use the formatter, but this is an easier way to get the minimum string
  2526. if (!this.isValid) return null;
  2527. let s = "P";
  2528. if (this.years !== 0) s += this.years + "Y";
  2529. if (this.months !== 0 || this.quarters !== 0) s += this.months + this.quarters * 3 + "M";
  2530. if (this.weeks !== 0) s += this.weeks + "W";
  2531. if (this.days !== 0) s += this.days + "D";
  2532. if (this.hours !== 0 || this.minutes !== 0 || this.seconds !== 0 || this.milliseconds !== 0) s += "T";
  2533. if (this.hours !== 0) s += this.hours + "H";
  2534. if (this.minutes !== 0) s += this.minutes + "M";
  2535. if (this.seconds !== 0 || this.milliseconds !== 0) // this will handle "floating point madness" by removing extra decimal places
  2536. // https://stackoverflow.com/questions/588004/is-floating-point-math-broken
  2537. s += roundTo(this.seconds + this.milliseconds / 1000, 3) + "S";
  2538. if (s === "P") s += "T0S";
  2539. return s;
  2540. }
  2541. /**
  2542. * Returns an ISO 8601-compliant string representation of this Duration, formatted as a time of day.
  2543. * Note that this will return null if the duration is invalid, negative, or equal to or greater than 24 hours.
  2544. * @see https://en.wikipedia.org/wiki/ISO_8601#Times
  2545. * @param {Object} opts - options
  2546. * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0
  2547. * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0
  2548. * @param {boolean} [opts.includePrefix=false] - include the `T` prefix
  2549. * @param {string} [opts.format='extended'] - choose between the basic and extended format
  2550. * @example Duration.fromObject({ hours: 11 }).toISOTime() //=> '11:00:00.000'
  2551. * @example Duration.fromObject({ hours: 11 }).toISOTime({ suppressMilliseconds: true }) //=> '11:00:00'
  2552. * @example Duration.fromObject({ hours: 11 }).toISOTime({ suppressSeconds: true }) //=> '11:00'
  2553. * @example Duration.fromObject({ hours: 11 }).toISOTime({ includePrefix: true }) //=> 'T11:00:00.000'
  2554. * @example Duration.fromObject({ hours: 11 }).toISOTime({ format: 'basic' }) //=> '110000.000'
  2555. * @return {string}
  2556. */
  2557. toISOTime(opts = {}) {
  2558. if (!this.isValid) return null;
  2559. const millis = this.toMillis();
  2560. if (millis < 0 || millis >= 86400000) return null;
  2561. opts = {
  2562. suppressMilliseconds: false,
  2563. suppressSeconds: false,
  2564. includePrefix: false,
  2565. format: "extended",
  2566. ...opts
  2567. };
  2568. const value = this.shiftTo("hours", "minutes", "seconds", "milliseconds");
  2569. let fmt = opts.format === "basic" ? "hhmm" : "hh:mm";
  2570. if (!opts.suppressSeconds || value.seconds !== 0 || value.milliseconds !== 0) {
  2571. fmt += opts.format === "basic" ? "ss" : ":ss";
  2572. if (!opts.suppressMilliseconds || value.milliseconds !== 0) {
  2573. fmt += ".SSS";
  2574. }
  2575. }
  2576. let str = value.toFormat(fmt);
  2577. if (opts.includePrefix) {
  2578. str = "T" + str;
  2579. }
  2580. return str;
  2581. }
  2582. /**
  2583. * Returns an ISO 8601 representation of this Duration appropriate for use in JSON.
  2584. * @return {string}
  2585. */
  2586. toJSON() {
  2587. return this.toISO();
  2588. }
  2589. /**
  2590. * Returns an ISO 8601 representation of this Duration appropriate for use in debugging.
  2591. * @return {string}
  2592. */
  2593. toString() {
  2594. return this.toISO();
  2595. }
  2596. /**
  2597. * Returns an milliseconds value of this Duration.
  2598. * @return {number}
  2599. */
  2600. toMillis() {
  2601. return this.as("milliseconds");
  2602. }
  2603. /**
  2604. * Returns an milliseconds value of this Duration. Alias of {@link toMillis}
  2605. * @return {number}
  2606. */
  2607. valueOf() {
  2608. return this.toMillis();
  2609. }
  2610. /**
  2611. * Make this Duration longer by the specified amount. Return a newly-constructed Duration.
  2612. * @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()
  2613. * @return {Duration}
  2614. */
  2615. plus(duration) {
  2616. if (!this.isValid) return this;
  2617. const dur = Duration.fromDurationLike(duration),
  2618. result = {};
  2619. for (const k of orderedUnits$1) {
  2620. if (hasOwnProperty(dur.values, k) || hasOwnProperty(this.values, k)) {
  2621. result[k] = dur.get(k) + this.get(k);
  2622. }
  2623. }
  2624. return clone$1(this, {
  2625. values: result
  2626. }, true);
  2627. }
  2628. /**
  2629. * Make this Duration shorter by the specified amount. Return a newly-constructed Duration.
  2630. * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()
  2631. * @return {Duration}
  2632. */
  2633. minus(duration) {
  2634. if (!this.isValid) return this;
  2635. const dur = Duration.fromDurationLike(duration);
  2636. return this.plus(dur.negate());
  2637. }
  2638. /**
  2639. * Scale this Duration by the specified amount. Return a newly-constructed Duration.
  2640. * @param {function} fn - The function to apply to each unit. Arity is 1 or 2: the value of the unit and, optionally, the unit name. Must return a number.
  2641. * @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnits(x => x * 2) //=> { hours: 2, minutes: 60 }
  2642. * @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnits((x, u) => u === "hours" ? x * 2 : x) //=> { hours: 2, minutes: 30 }
  2643. * @return {Duration}
  2644. */
  2645. mapUnits(fn) {
  2646. if (!this.isValid) return this;
  2647. const result = {};
  2648. for (const k of Object.keys(this.values)) {
  2649. result[k] = asNumber(fn(this.values[k], k));
  2650. }
  2651. return clone$1(this, {
  2652. values: result
  2653. }, true);
  2654. }
  2655. /**
  2656. * Get the value of unit.
  2657. * @param {string} unit - a unit such as 'minute' or 'day'
  2658. * @example Duration.fromObject({years: 2, days: 3}).get('years') //=> 2
  2659. * @example Duration.fromObject({years: 2, days: 3}).get('months') //=> 0
  2660. * @example Duration.fromObject({years: 2, days: 3}).get('days') //=> 3
  2661. * @return {number}
  2662. */
  2663. get(unit) {
  2664. return this[Duration.normalizeUnit(unit)];
  2665. }
  2666. /**
  2667. * "Set" the values of specified units. Return a newly-constructed Duration.
  2668. * @param {Object} values - a mapping of units to numbers
  2669. * @example dur.set({ years: 2017 })
  2670. * @example dur.set({ hours: 8, minutes: 30 })
  2671. * @return {Duration}
  2672. */
  2673. set(values) {
  2674. if (!this.isValid) return this;
  2675. const mixed = { ...this.values,
  2676. ...normalizeObject(values, Duration.normalizeUnit)
  2677. };
  2678. return clone$1(this, {
  2679. values: mixed
  2680. });
  2681. }
  2682. /**
  2683. * "Set" the locale and/or numberingSystem. Returns a newly-constructed Duration.
  2684. * @example dur.reconfigure({ locale: 'en-GB' })
  2685. * @return {Duration}
  2686. */
  2687. reconfigure({
  2688. locale,
  2689. numberingSystem,
  2690. conversionAccuracy,
  2691. matrix
  2692. } = {}) {
  2693. const loc = this.loc.clone({
  2694. locale,
  2695. numberingSystem
  2696. });
  2697. const opts = {
  2698. loc,
  2699. matrix,
  2700. conversionAccuracy
  2701. };
  2702. return clone$1(this, opts);
  2703. }
  2704. /**
  2705. * Return the length of the duration in the specified unit.
  2706. * @param {string} unit - a unit such as 'minutes' or 'days'
  2707. * @example Duration.fromObject({years: 1}).as('days') //=> 365
  2708. * @example Duration.fromObject({years: 1}).as('months') //=> 12
  2709. * @example Duration.fromObject({hours: 60}).as('days') //=> 2.5
  2710. * @return {number}
  2711. */
  2712. as(unit) {
  2713. return this.isValid ? this.shiftTo(unit).get(unit) : NaN;
  2714. }
  2715. /**
  2716. * Reduce this Duration to its canonical representation in its current units.
  2717. * @example Duration.fromObject({ years: 2, days: 5000 }).normalize().toObject() //=> { years: 15, days: 255 }
  2718. * @example Duration.fromObject({ hours: 12, minutes: -45 }).normalize().toObject() //=> { hours: 11, minutes: 15 }
  2719. * @return {Duration}
  2720. */
  2721. normalize() {
  2722. if (!this.isValid) return this;
  2723. const vals = this.toObject();
  2724. normalizeValues(this.matrix, vals);
  2725. return clone$1(this, {
  2726. values: vals
  2727. }, true);
  2728. }
  2729. /**
  2730. * Convert this Duration into its representation in a different set of units.
  2731. * @example Duration.fromObject({ hours: 1, seconds: 30 }).shiftTo('minutes', 'milliseconds').toObject() //=> { minutes: 60, milliseconds: 30000 }
  2732. * @return {Duration}
  2733. */
  2734. shiftTo(...units) {
  2735. if (!this.isValid) return this;
  2736. if (units.length === 0) {
  2737. return this;
  2738. }
  2739. units = units.map(u => Duration.normalizeUnit(u));
  2740. const built = {},
  2741. accumulated = {},
  2742. vals = this.toObject();
  2743. let lastUnit;
  2744. for (const k of orderedUnits$1) {
  2745. if (units.indexOf(k) >= 0) {
  2746. lastUnit = k;
  2747. let own = 0; // anything we haven't boiled down yet should get boiled to this unit
  2748. for (const ak in accumulated) {
  2749. own += this.matrix[ak][k] * accumulated[ak];
  2750. accumulated[ak] = 0;
  2751. } // plus anything that's already in this unit
  2752. if (isNumber(vals[k])) {
  2753. own += vals[k];
  2754. }
  2755. const i = Math.trunc(own);
  2756. built[k] = i;
  2757. accumulated[k] = (own * 1000 - i * 1000) / 1000; // plus anything further down the chain that should be rolled up in to this
  2758. for (const down in vals) {
  2759. if (orderedUnits$1.indexOf(down) > orderedUnits$1.indexOf(k)) {
  2760. convert(this.matrix, vals, down, built, k);
  2761. }
  2762. } // otherwise, keep it in the wings to boil it later
  2763. } else if (isNumber(vals[k])) {
  2764. accumulated[k] = vals[k];
  2765. }
  2766. } // anything leftover becomes the decimal for the last unit
  2767. // lastUnit must be defined since units is not empty
  2768. for (const key in accumulated) {
  2769. if (accumulated[key] !== 0) {
  2770. built[lastUnit] += key === lastUnit ? accumulated[key] : accumulated[key] / this.matrix[lastUnit][key];
  2771. }
  2772. }
  2773. return clone$1(this, {
  2774. values: built
  2775. }, true).normalize();
  2776. }
  2777. /**
  2778. * Return the negative of this Duration.
  2779. * @example Duration.fromObject({ hours: 1, seconds: 30 }).negate().toObject() //=> { hours: -1, seconds: -30 }
  2780. * @return {Duration}
  2781. */
  2782. negate() {
  2783. if (!this.isValid) return this;
  2784. const negated = {};
  2785. for (const k of Object.keys(this.values)) {
  2786. negated[k] = this.values[k] === 0 ? 0 : -this.values[k];
  2787. }
  2788. return clone$1(this, {
  2789. values: negated
  2790. }, true);
  2791. }
  2792. /**
  2793. * Get the years.
  2794. * @type {number}
  2795. */
  2796. get years() {
  2797. return this.isValid ? this.values.years || 0 : NaN;
  2798. }
  2799. /**
  2800. * Get the quarters.
  2801. * @type {number}
  2802. */
  2803. get quarters() {
  2804. return this.isValid ? this.values.quarters || 0 : NaN;
  2805. }
  2806. /**
  2807. * Get the months.
  2808. * @type {number}
  2809. */
  2810. get months() {
  2811. return this.isValid ? this.values.months || 0 : NaN;
  2812. }
  2813. /**
  2814. * Get the weeks
  2815. * @type {number}
  2816. */
  2817. get weeks() {
  2818. return this.isValid ? this.values.weeks || 0 : NaN;
  2819. }
  2820. /**
  2821. * Get the days.
  2822. * @type {number}
  2823. */
  2824. get days() {
  2825. return this.isValid ? this.values.days || 0 : NaN;
  2826. }
  2827. /**
  2828. * Get the hours.
  2829. * @type {number}
  2830. */
  2831. get hours() {
  2832. return this.isValid ? this.values.hours || 0 : NaN;
  2833. }
  2834. /**
  2835. * Get the minutes.
  2836. * @type {number}
  2837. */
  2838. get minutes() {
  2839. return this.isValid ? this.values.minutes || 0 : NaN;
  2840. }
  2841. /**
  2842. * Get the seconds.
  2843. * @return {number}
  2844. */
  2845. get seconds() {
  2846. return this.isValid ? this.values.seconds || 0 : NaN;
  2847. }
  2848. /**
  2849. * Get the milliseconds.
  2850. * @return {number}
  2851. */
  2852. get milliseconds() {
  2853. return this.isValid ? this.values.milliseconds || 0 : NaN;
  2854. }
  2855. /**
  2856. * Returns whether the Duration is invalid. Invalid durations are returned by diff operations
  2857. * on invalid DateTimes or Intervals.
  2858. * @return {boolean}
  2859. */
  2860. get isValid() {
  2861. return this.invalid === null;
  2862. }
  2863. /**
  2864. * Returns an error code if this Duration became invalid, or null if the Duration is valid
  2865. * @return {string}
  2866. */
  2867. get invalidReason() {
  2868. return this.invalid ? this.invalid.reason : null;
  2869. }
  2870. /**
  2871. * Returns an explanation of why this Duration became invalid, or null if the Duration is valid
  2872. * @type {string}
  2873. */
  2874. get invalidExplanation() {
  2875. return this.invalid ? this.invalid.explanation : null;
  2876. }
  2877. /**
  2878. * Equality check
  2879. * Two Durations are equal iff they have the same units and the same values for each unit.
  2880. * @param {Duration} other
  2881. * @return {boolean}
  2882. */
  2883. equals(other) {
  2884. if (!this.isValid || !other.isValid) {
  2885. return false;
  2886. }
  2887. if (!this.loc.equals(other.loc)) {
  2888. return false;
  2889. }
  2890. function eq(v1, v2) {
  2891. // Consider 0 and undefined as equal
  2892. if (v1 === undefined || v1 === 0) return v2 === undefined || v2 === 0;
  2893. return v1 === v2;
  2894. }
  2895. for (const u of orderedUnits$1) {
  2896. if (!eq(this.values[u], other.values[u])) {
  2897. return false;
  2898. }
  2899. }
  2900. return true;
  2901. }
  2902. }
  2903. const INVALID$1 = "Invalid Interval"; // checks if the start is equal to or before the end
  2904. function validateStartEnd(start, end) {
  2905. if (!start || !start.isValid) {
  2906. return Interval.invalid("missing or invalid start");
  2907. } else if (!end || !end.isValid) {
  2908. return Interval.invalid("missing or invalid end");
  2909. } else if (end < start) {
  2910. return Interval.invalid("end before start", `The end of an interval must be after its start, but you had start=${start.toISO()} and end=${end.toISO()}`);
  2911. } else {
  2912. return null;
  2913. }
  2914. }
  2915. /**
  2916. * An Interval object represents a half-open interval of time, where each endpoint is a {@link DateTime}. Conceptually, it's a container for those two endpoints, accompanied by methods for creating, parsing, interrogating, comparing, transforming, and formatting them.
  2917. *
  2918. * Here is a brief overview of the most commonly used methods and getters in Interval:
  2919. *
  2920. * * **Creation** To create an Interval, use {@link Interval.fromDateTimes}, {@link Interval.after}, {@link Interval.before}, or {@link Interval.fromISO}.
  2921. * * **Accessors** Use {@link Interval#start} and {@link Interval#end} to get the start and end.
  2922. * * **Interrogation** To analyze the Interval, use {@link Interval#count}, {@link Interval#length}, {@link Interval#hasSame}, {@link Interval#contains}, {@link Interval#isAfter}, or {@link Interval#isBefore}.
  2923. * * **Transformation** To create other Intervals out of this one, use {@link Interval#set}, {@link Interval#splitAt}, {@link Interval#splitBy}, {@link Interval#divideEqually}, {@link Interval.merge}, {@link Interval.xor}, {@link Interval#union}, {@link Interval#intersection}, or {@link Interval#difference}.
  2924. * * **Comparison** To compare this Interval to another one, use {@link Interval#equals}, {@link Interval#overlaps}, {@link Interval#abutsStart}, {@link Interval#abutsEnd}, {@link Interval#engulfs}
  2925. * * **Output** To convert the Interval into other representations, see {@link Interval#toString}, {@link Interval#toISO}, {@link Interval#toISODate}, {@link Interval#toISOTime}, {@link Interval#toFormat}, and {@link Interval#toDuration}.
  2926. */
  2927. class Interval {
  2928. /**
  2929. * @private
  2930. */
  2931. constructor(config) {
  2932. /**
  2933. * @access private
  2934. */
  2935. this.s = config.start;
  2936. /**
  2937. * @access private
  2938. */
  2939. this.e = config.end;
  2940. /**
  2941. * @access private
  2942. */
  2943. this.invalid = config.invalid || null;
  2944. /**
  2945. * @access private
  2946. */
  2947. this.isLuxonInterval = true;
  2948. }
  2949. /**
  2950. * Create an invalid Interval.
  2951. * @param {string} reason - simple string of why this Interval is invalid. Should not contain parameters or anything else data-dependent
  2952. * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information
  2953. * @return {Interval}
  2954. */
  2955. static invalid(reason, explanation = null) {
  2956. if (!reason) {
  2957. throw new InvalidArgumentError("need to specify a reason the Interval is invalid");
  2958. }
  2959. const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
  2960. if (Settings.throwOnInvalid) {
  2961. throw new InvalidIntervalError(invalid);
  2962. } else {
  2963. return new Interval({
  2964. invalid
  2965. });
  2966. }
  2967. }
  2968. /**
  2969. * Create an Interval from a start DateTime and an end DateTime. Inclusive of the start but not the end.
  2970. * @param {DateTime|Date|Object} start
  2971. * @param {DateTime|Date|Object} end
  2972. * @return {Interval}
  2973. */
  2974. static fromDateTimes(start, end) {
  2975. const builtStart = friendlyDateTime(start),
  2976. builtEnd = friendlyDateTime(end);
  2977. const validateError = validateStartEnd(builtStart, builtEnd);
  2978. if (validateError == null) {
  2979. return new Interval({
  2980. start: builtStart,
  2981. end: builtEnd
  2982. });
  2983. } else {
  2984. return validateError;
  2985. }
  2986. }
  2987. /**
  2988. * Create an Interval from a start DateTime and a Duration to extend to.
  2989. * @param {DateTime|Date|Object} start
  2990. * @param {Duration|Object|number} duration - the length of the Interval.
  2991. * @return {Interval}
  2992. */
  2993. static after(start, duration) {
  2994. const dur = Duration.fromDurationLike(duration),
  2995. dt = friendlyDateTime(start);
  2996. return Interval.fromDateTimes(dt, dt.plus(dur));
  2997. }
  2998. /**
  2999. * Create an Interval from an end DateTime and a Duration to extend backwards to.
  3000. * @param {DateTime|Date|Object} end
  3001. * @param {Duration|Object|number} duration - the length of the Interval.
  3002. * @return {Interval}
  3003. */
  3004. static before(end, duration) {
  3005. const dur = Duration.fromDurationLike(duration),
  3006. dt = friendlyDateTime(end);
  3007. return Interval.fromDateTimes(dt.minus(dur), dt);
  3008. }
  3009. /**
  3010. * Create an Interval from an ISO 8601 string.
  3011. * Accepts `<start>/<end>`, `<start>/<duration>`, and `<duration>/<end>` formats.
  3012. * @param {string} text - the ISO string to parse
  3013. * @param {Object} [opts] - options to pass {@link DateTime#fromISO} and optionally {@link Duration#fromISO}
  3014. * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals
  3015. * @return {Interval}
  3016. */
  3017. static fromISO(text, opts) {
  3018. const [s, e] = (text || "").split("/", 2);
  3019. if (s && e) {
  3020. let start, startIsValid;
  3021. try {
  3022. start = DateTime.fromISO(s, opts);
  3023. startIsValid = start.isValid;
  3024. } catch (e) {
  3025. startIsValid = false;
  3026. }
  3027. let end, endIsValid;
  3028. try {
  3029. end = DateTime.fromISO(e, opts);
  3030. endIsValid = end.isValid;
  3031. } catch (e) {
  3032. endIsValid = false;
  3033. }
  3034. if (startIsValid && endIsValid) {
  3035. return Interval.fromDateTimes(start, end);
  3036. }
  3037. if (startIsValid) {
  3038. const dur = Duration.fromISO(e, opts);
  3039. if (dur.isValid) {
  3040. return Interval.after(start, dur);
  3041. }
  3042. } else if (endIsValid) {
  3043. const dur = Duration.fromISO(s, opts);
  3044. if (dur.isValid) {
  3045. return Interval.before(end, dur);
  3046. }
  3047. }
  3048. }
  3049. return Interval.invalid("unparsable", `the input "${text}" can't be parsed as ISO 8601`);
  3050. }
  3051. /**
  3052. * Check if an object is an Interval. Works across context boundaries
  3053. * @param {object} o
  3054. * @return {boolean}
  3055. */
  3056. static isInterval(o) {
  3057. return o && o.isLuxonInterval || false;
  3058. }
  3059. /**
  3060. * Returns the start of the Interval
  3061. * @type {DateTime}
  3062. */
  3063. get start() {
  3064. return this.isValid ? this.s : null;
  3065. }
  3066. /**
  3067. * Returns the end of the Interval
  3068. * @type {DateTime}
  3069. */
  3070. get end() {
  3071. return this.isValid ? this.e : null;
  3072. }
  3073. /**
  3074. * Returns whether this Interval's end is at least its start, meaning that the Interval isn't 'backwards'.
  3075. * @type {boolean}
  3076. */
  3077. get isValid() {
  3078. return this.invalidReason === null;
  3079. }
  3080. /**
  3081. * Returns an error code if this Interval is invalid, or null if the Interval is valid
  3082. * @type {string}
  3083. */
  3084. get invalidReason() {
  3085. return this.invalid ? this.invalid.reason : null;
  3086. }
  3087. /**
  3088. * Returns an explanation of why this Interval became invalid, or null if the Interval is valid
  3089. * @type {string}
  3090. */
  3091. get invalidExplanation() {
  3092. return this.invalid ? this.invalid.explanation : null;
  3093. }
  3094. /**
  3095. * Returns the length of the Interval in the specified unit.
  3096. * @param {string} unit - the unit (such as 'hours' or 'days') to return the length in.
  3097. * @return {number}
  3098. */
  3099. length(unit = "milliseconds") {
  3100. return this.isValid ? this.toDuration(...[unit]).get(unit) : NaN;
  3101. }
  3102. /**
  3103. * Returns the count of minutes, hours, days, months, or years included in the Interval, even in part.
  3104. * Unlike {@link Interval#length} this counts sections of the calendar, not periods of time, e.g. specifying 'day'
  3105. * asks 'what dates are included in this interval?', not 'how many days long is this interval?'
  3106. * @param {string} [unit='milliseconds'] - the unit of time to count.
  3107. * @return {number}
  3108. */
  3109. count(unit = "milliseconds") {
  3110. if (!this.isValid) return NaN;
  3111. const start = this.start.startOf(unit),
  3112. end = this.end.startOf(unit);
  3113. return Math.floor(end.diff(start, unit).get(unit)) + 1;
  3114. }
  3115. /**
  3116. * Returns whether this Interval's start and end are both in the same unit of time
  3117. * @param {string} unit - the unit of time to check sameness on
  3118. * @return {boolean}
  3119. */
  3120. hasSame(unit) {
  3121. return this.isValid ? this.isEmpty() || this.e.minus(1).hasSame(this.s, unit) : false;
  3122. }
  3123. /**
  3124. * Return whether this Interval has the same start and end DateTimes.
  3125. * @return {boolean}
  3126. */
  3127. isEmpty() {
  3128. return this.s.valueOf() === this.e.valueOf();
  3129. }
  3130. /**
  3131. * Return whether this Interval's start is after the specified DateTime.
  3132. * @param {DateTime} dateTime
  3133. * @return {boolean}
  3134. */
  3135. isAfter(dateTime) {
  3136. if (!this.isValid) return false;
  3137. return this.s > dateTime;
  3138. }
  3139. /**
  3140. * Return whether this Interval's end is before the specified DateTime.
  3141. * @param {DateTime} dateTime
  3142. * @return {boolean}
  3143. */
  3144. isBefore(dateTime) {
  3145. if (!this.isValid) return false;
  3146. return this.e <= dateTime;
  3147. }
  3148. /**
  3149. * Return whether this Interval contains the specified DateTime.
  3150. * @param {DateTime} dateTime
  3151. * @return {boolean}
  3152. */
  3153. contains(dateTime) {
  3154. if (!this.isValid) return false;
  3155. return this.s <= dateTime && this.e > dateTime;
  3156. }
  3157. /**
  3158. * "Sets" the start and/or end dates. Returns a newly-constructed Interval.
  3159. * @param {Object} values - the values to set
  3160. * @param {DateTime} values.start - the starting DateTime
  3161. * @param {DateTime} values.end - the ending DateTime
  3162. * @return {Interval}
  3163. */
  3164. set({
  3165. start,
  3166. end
  3167. } = {}) {
  3168. if (!this.isValid) return this;
  3169. return Interval.fromDateTimes(start || this.s, end || this.e);
  3170. }
  3171. /**
  3172. * Split this Interval at each of the specified DateTimes
  3173. * @param {...DateTime} dateTimes - the unit of time to count.
  3174. * @return {Array}
  3175. */
  3176. splitAt(...dateTimes) {
  3177. if (!this.isValid) return [];
  3178. const sorted = dateTimes.map(friendlyDateTime).filter(d => this.contains(d)).sort(),
  3179. results = [];
  3180. let {
  3181. s
  3182. } = this,
  3183. i = 0;
  3184. while (s < this.e) {
  3185. const added = sorted[i] || this.e,
  3186. next = +added > +this.e ? this.e : added;
  3187. results.push(Interval.fromDateTimes(s, next));
  3188. s = next;
  3189. i += 1;
  3190. }
  3191. return results;
  3192. }
  3193. /**
  3194. * Split this Interval into smaller Intervals, each of the specified length.
  3195. * Left over time is grouped into a smaller interval
  3196. * @param {Duration|Object|number} duration - The length of each resulting interval.
  3197. * @return {Array}
  3198. */
  3199. splitBy(duration) {
  3200. const dur = Duration.fromDurationLike(duration);
  3201. if (!this.isValid || !dur.isValid || dur.as("milliseconds") === 0) {
  3202. return [];
  3203. }
  3204. let {
  3205. s
  3206. } = this,
  3207. idx = 1,
  3208. next;
  3209. const results = [];
  3210. while (s < this.e) {
  3211. const added = this.start.plus(dur.mapUnits(x => x * idx));
  3212. next = +added > +this.e ? this.e : added;
  3213. results.push(Interval.fromDateTimes(s, next));
  3214. s = next;
  3215. idx += 1;
  3216. }
  3217. return results;
  3218. }
  3219. /**
  3220. * Split this Interval into the specified number of smaller intervals.
  3221. * @param {number} numberOfParts - The number of Intervals to divide the Interval into.
  3222. * @return {Array}
  3223. */
  3224. divideEqually(numberOfParts) {
  3225. if (!this.isValid) return [];
  3226. return this.splitBy(this.length() / numberOfParts).slice(0, numberOfParts);
  3227. }
  3228. /**
  3229. * Return whether this Interval overlaps with the specified Interval
  3230. * @param {Interval} other
  3231. * @return {boolean}
  3232. */
  3233. overlaps(other) {
  3234. return this.e > other.s && this.s < other.e;
  3235. }
  3236. /**
  3237. * Return whether this Interval's end is adjacent to the specified Interval's start.
  3238. * @param {Interval} other
  3239. * @return {boolean}
  3240. */
  3241. abutsStart(other) {
  3242. if (!this.isValid) return false;
  3243. return +this.e === +other.s;
  3244. }
  3245. /**
  3246. * Return whether this Interval's start is adjacent to the specified Interval's end.
  3247. * @param {Interval} other
  3248. * @return {boolean}
  3249. */
  3250. abutsEnd(other) {
  3251. if (!this.isValid) return false;
  3252. return +other.e === +this.s;
  3253. }
  3254. /**
  3255. * Return whether this Interval engulfs the start and end of the specified Interval.
  3256. * @param {Interval} other
  3257. * @return {boolean}
  3258. */
  3259. engulfs(other) {
  3260. if (!this.isValid) return false;
  3261. return this.s <= other.s && this.e >= other.e;
  3262. }
  3263. /**
  3264. * Return whether this Interval has the same start and end as the specified Interval.
  3265. * @param {Interval} other
  3266. * @return {boolean}
  3267. */
  3268. equals(other) {
  3269. if (!this.isValid || !other.isValid) {
  3270. return false;
  3271. }
  3272. return this.s.equals(other.s) && this.e.equals(other.e);
  3273. }
  3274. /**
  3275. * Return an Interval representing the intersection of this Interval and the specified Interval.
  3276. * Specifically, the resulting Interval has the maximum start time and the minimum end time of the two Intervals.
  3277. * Returns null if the intersection is empty, meaning, the intervals don't intersect.
  3278. * @param {Interval} other
  3279. * @return {Interval}
  3280. */
  3281. intersection(other) {
  3282. if (!this.isValid) return this;
  3283. const s = this.s > other.s ? this.s : other.s,
  3284. e = this.e < other.e ? this.e : other.e;
  3285. if (s >= e) {
  3286. return null;
  3287. } else {
  3288. return Interval.fromDateTimes(s, e);
  3289. }
  3290. }
  3291. /**
  3292. * Return an Interval representing the union of this Interval and the specified Interval.
  3293. * Specifically, the resulting Interval has the minimum start time and the maximum end time of the two Intervals.
  3294. * @param {Interval} other
  3295. * @return {Interval}
  3296. */
  3297. union(other) {
  3298. if (!this.isValid) return this;
  3299. const s = this.s < other.s ? this.s : other.s,
  3300. e = this.e > other.e ? this.e : other.e;
  3301. return Interval.fromDateTimes(s, e);
  3302. }
  3303. /**
  3304. * Merge an array of Intervals into a equivalent minimal set of Intervals.
  3305. * Combines overlapping and adjacent Intervals.
  3306. * @param {Array} intervals
  3307. * @return {Array}
  3308. */
  3309. static merge(intervals) {
  3310. const [found, final] = intervals.sort((a, b) => a.s - b.s).reduce(([sofar, current], item) => {
  3311. if (!current) {
  3312. return [sofar, item];
  3313. } else if (current.overlaps(item) || current.abutsStart(item)) {
  3314. return [sofar, current.union(item)];
  3315. } else {
  3316. return [sofar.concat([current]), item];
  3317. }
  3318. }, [[], null]);
  3319. if (final) {
  3320. found.push(final);
  3321. }
  3322. return found;
  3323. }
  3324. /**
  3325. * Return an array of Intervals representing the spans of time that only appear in one of the specified Intervals.
  3326. * @param {Array} intervals
  3327. * @return {Array}
  3328. */
  3329. static xor(intervals) {
  3330. let start = null,
  3331. currentCount = 0;
  3332. const results = [],
  3333. ends = intervals.map(i => [{
  3334. time: i.s,
  3335. type: "s"
  3336. }, {
  3337. time: i.e,
  3338. type: "e"
  3339. }]),
  3340. flattened = Array.prototype.concat(...ends),
  3341. arr = flattened.sort((a, b) => a.time - b.time);
  3342. for (const i of arr) {
  3343. currentCount += i.type === "s" ? 1 : -1;
  3344. if (currentCount === 1) {
  3345. start = i.time;
  3346. } else {
  3347. if (start && +start !== +i.time) {
  3348. results.push(Interval.fromDateTimes(start, i.time));
  3349. }
  3350. start = null;
  3351. }
  3352. }
  3353. return Interval.merge(results);
  3354. }
  3355. /**
  3356. * Return an Interval representing the span of time in this Interval that doesn't overlap with any of the specified Intervals.
  3357. * @param {...Interval} intervals
  3358. * @return {Array}
  3359. */
  3360. difference(...intervals) {
  3361. return Interval.xor([this].concat(intervals)).map(i => this.intersection(i)).filter(i => i && !i.isEmpty());
  3362. }
  3363. /**
  3364. * Returns a string representation of this Interval appropriate for debugging.
  3365. * @return {string}
  3366. */
  3367. toString() {
  3368. if (!this.isValid) return INVALID$1;
  3369. return `[${this.s.toISO()} – ${this.e.toISO()})`;
  3370. }
  3371. /**
  3372. * Returns an ISO 8601-compliant string representation of this Interval.
  3373. * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals
  3374. * @param {Object} opts - The same options as {@link DateTime#toISO}
  3375. * @return {string}
  3376. */
  3377. toISO(opts) {
  3378. if (!this.isValid) return INVALID$1;
  3379. return `${this.s.toISO(opts)}/${this.e.toISO(opts)}`;
  3380. }
  3381. /**
  3382. * Returns an ISO 8601-compliant string representation of date of this Interval.
  3383. * The time components are ignored.
  3384. * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals
  3385. * @return {string}
  3386. */
  3387. toISODate() {
  3388. if (!this.isValid) return INVALID$1;
  3389. return `${this.s.toISODate()}/${this.e.toISODate()}`;
  3390. }
  3391. /**
  3392. * Returns an ISO 8601-compliant string representation of time of this Interval.
  3393. * The date components are ignored.
  3394. * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals
  3395. * @param {Object} opts - The same options as {@link DateTime#toISO}
  3396. * @return {string}
  3397. */
  3398. toISOTime(opts) {
  3399. if (!this.isValid) return INVALID$1;
  3400. return `${this.s.toISOTime(opts)}/${this.e.toISOTime(opts)}`;
  3401. }
  3402. /**
  3403. * Returns a string representation of this Interval formatted according to the specified format string.
  3404. * @param {string} dateFormat - the format string. This string formats the start and end time. See {@link DateTime#toFormat} for details.
  3405. * @param {Object} opts - options
  3406. * @param {string} [opts.separator = ' – '] - a separator to place between the start and end representations
  3407. * @return {string}
  3408. */
  3409. toFormat(dateFormat, {
  3410. separator = " – "
  3411. } = {}) {
  3412. if (!this.isValid) return INVALID$1;
  3413. return `${this.s.toFormat(dateFormat)}${separator}${this.e.toFormat(dateFormat)}`;
  3414. }
  3415. /**
  3416. * Return a Duration representing the time spanned by this interval.
  3417. * @param {string|string[]} [unit=['milliseconds']] - the unit or units (such as 'hours' or 'days') to include in the duration.
  3418. * @param {Object} opts - options that affect the creation of the Duration
  3419. * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
  3420. * @example Interval.fromDateTimes(dt1, dt2).toDuration().toObject() //=> { milliseconds: 88489257 }
  3421. * @example Interval.fromDateTimes(dt1, dt2).toDuration('days').toObject() //=> { days: 1.0241812152777778 }
  3422. * @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes']).toObject() //=> { hours: 24, minutes: 34.82095 }
  3423. * @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes', 'seconds']).toObject() //=> { hours: 24, minutes: 34, seconds: 49.257 }
  3424. * @example Interval.fromDateTimes(dt1, dt2).toDuration('seconds').toObject() //=> { seconds: 88489.257 }
  3425. * @return {Duration}
  3426. */
  3427. toDuration(unit, opts) {
  3428. if (!this.isValid) {
  3429. return Duration.invalid(this.invalidReason);
  3430. }
  3431. return this.e.diff(this.s, unit, opts);
  3432. }
  3433. /**
  3434. * Run mapFn on the interval start and end, returning a new Interval from the resulting DateTimes
  3435. * @param {function} mapFn
  3436. * @return {Interval}
  3437. * @example Interval.fromDateTimes(dt1, dt2).mapEndpoints(endpoint => endpoint.toUTC())
  3438. * @example Interval.fromDateTimes(dt1, dt2).mapEndpoints(endpoint => endpoint.plus({ hours: 2 }))
  3439. */
  3440. mapEndpoints(mapFn) {
  3441. return Interval.fromDateTimes(mapFn(this.s), mapFn(this.e));
  3442. }
  3443. }
  3444. /**
  3445. * The Info class contains static methods for retrieving general time and date related data. For example, it has methods for finding out if a time zone has a DST, for listing the months in any supported locale, and for discovering which of Luxon features are available in the current environment.
  3446. */
  3447. class Info {
  3448. /**
  3449. * Return whether the specified zone contains a DST.
  3450. * @param {string|Zone} [zone='local'] - Zone to check. Defaults to the environment's local zone.
  3451. * @return {boolean}
  3452. */
  3453. static hasDST(zone = Settings.defaultZone) {
  3454. const proto = DateTime.now().setZone(zone).set({
  3455. month: 12
  3456. });
  3457. return !zone.isUniversal && proto.offset !== proto.set({
  3458. month: 6
  3459. }).offset;
  3460. }
  3461. /**
  3462. * Return whether the specified zone is a valid IANA specifier.
  3463. * @param {string} zone - Zone to check
  3464. * @return {boolean}
  3465. */
  3466. static isValidIANAZone(zone) {
  3467. return IANAZone.isValidZone(zone);
  3468. }
  3469. /**
  3470. * Converts the input into a {@link Zone} instance.
  3471. *
  3472. * * If `input` is already a Zone instance, it is returned unchanged.
  3473. * * If `input` is a string containing a valid time zone name, a Zone instance
  3474. * with that name is returned.
  3475. * * If `input` is a string that doesn't refer to a known time zone, a Zone
  3476. * instance with {@link Zone#isValid} == false is returned.
  3477. * * If `input is a number, a Zone instance with the specified fixed offset
  3478. * in minutes is returned.
  3479. * * If `input` is `null` or `undefined`, the default zone is returned.
  3480. * @param {string|Zone|number} [input] - the value to be converted
  3481. * @return {Zone}
  3482. */
  3483. static normalizeZone(input) {
  3484. return normalizeZone(input, Settings.defaultZone);
  3485. }
  3486. /**
  3487. * Return an array of standalone month names.
  3488. * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
  3489. * @param {string} [length='long'] - the length of the month representation, such as "numeric", "2-digit", "narrow", "short", "long"
  3490. * @param {Object} opts - options
  3491. * @param {string} [opts.locale] - the locale code
  3492. * @param {string} [opts.numberingSystem=null] - the numbering system
  3493. * @param {string} [opts.locObj=null] - an existing locale object to use
  3494. * @param {string} [opts.outputCalendar='gregory'] - the calendar
  3495. * @example Info.months()[0] //=> 'January'
  3496. * @example Info.months('short')[0] //=> 'Jan'
  3497. * @example Info.months('numeric')[0] //=> '1'
  3498. * @example Info.months('short', { locale: 'fr-CA' } )[0] //=> 'janv.'
  3499. * @example Info.months('numeric', { locale: 'ar' })[0] //=> '١'
  3500. * @example Info.months('long', { outputCalendar: 'islamic' })[0] //=> 'Rabiʻ I'
  3501. * @return {Array}
  3502. */
  3503. static months(length = "long", {
  3504. locale = null,
  3505. numberingSystem = null,
  3506. locObj = null,
  3507. outputCalendar = "gregory"
  3508. } = {}) {
  3509. return (locObj || Locale.create(locale, numberingSystem, outputCalendar)).months(length);
  3510. }
  3511. /**
  3512. * Return an array of format month names.
  3513. * Format months differ from standalone months in that they're meant to appear next to the day of the month. In some languages, that
  3514. * changes the string.
  3515. * See {@link Info#months}
  3516. * @param {string} [length='long'] - the length of the month representation, such as "numeric", "2-digit", "narrow", "short", "long"
  3517. * @param {Object} opts - options
  3518. * @param {string} [opts.locale] - the locale code
  3519. * @param {string} [opts.numberingSystem=null] - the numbering system
  3520. * @param {string} [opts.locObj=null] - an existing locale object to use
  3521. * @param {string} [opts.outputCalendar='gregory'] - the calendar
  3522. * @return {Array}
  3523. */
  3524. static monthsFormat(length = "long", {
  3525. locale = null,
  3526. numberingSystem = null,
  3527. locObj = null,
  3528. outputCalendar = "gregory"
  3529. } = {}) {
  3530. return (locObj || Locale.create(locale, numberingSystem, outputCalendar)).months(length, true);
  3531. }
  3532. /**
  3533. * Return an array of standalone week names.
  3534. * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
  3535. * @param {string} [length='long'] - the length of the weekday representation, such as "narrow", "short", "long".
  3536. * @param {Object} opts - options
  3537. * @param {string} [opts.locale] - the locale code
  3538. * @param {string} [opts.numberingSystem=null] - the numbering system
  3539. * @param {string} [opts.locObj=null] - an existing locale object to use
  3540. * @example Info.weekdays()[0] //=> 'Monday'
  3541. * @example Info.weekdays('short')[0] //=> 'Mon'
  3542. * @example Info.weekdays('short', { locale: 'fr-CA' })[0] //=> 'lun.'
  3543. * @example Info.weekdays('short', { locale: 'ar' })[0] //=> 'الاثنين'
  3544. * @return {Array}
  3545. */
  3546. static weekdays(length = "long", {
  3547. locale = null,
  3548. numberingSystem = null,
  3549. locObj = null
  3550. } = {}) {
  3551. return (locObj || Locale.create(locale, numberingSystem, null)).weekdays(length);
  3552. }
  3553. /**
  3554. * Return an array of format week names.
  3555. * Format weekdays differ from standalone weekdays in that they're meant to appear next to more date information. In some languages, that
  3556. * changes the string.
  3557. * See {@link Info#weekdays}
  3558. * @param {string} [length='long'] - the length of the month representation, such as "narrow", "short", "long".
  3559. * @param {Object} opts - options
  3560. * @param {string} [opts.locale=null] - the locale code
  3561. * @param {string} [opts.numberingSystem=null] - the numbering system
  3562. * @param {string} [opts.locObj=null] - an existing locale object to use
  3563. * @return {Array}
  3564. */
  3565. static weekdaysFormat(length = "long", {
  3566. locale = null,
  3567. numberingSystem = null,
  3568. locObj = null
  3569. } = {}) {
  3570. return (locObj || Locale.create(locale, numberingSystem, null)).weekdays(length, true);
  3571. }
  3572. /**
  3573. * Return an array of meridiems.
  3574. * @param {Object} opts - options
  3575. * @param {string} [opts.locale] - the locale code
  3576. * @example Info.meridiems() //=> [ 'AM', 'PM' ]
  3577. * @example Info.meridiems({ locale: 'my' }) //=> [ 'နံနက်', 'ညနေ' ]
  3578. * @return {Array}
  3579. */
  3580. static meridiems({
  3581. locale = null
  3582. } = {}) {
  3583. return Locale.create(locale).meridiems();
  3584. }
  3585. /**
  3586. * Return an array of eras, such as ['BC', 'AD']. The locale can be specified, but the calendar system is always Gregorian.
  3587. * @param {string} [length='short'] - the length of the era representation, such as "short" or "long".
  3588. * @param {Object} opts - options
  3589. * @param {string} [opts.locale] - the locale code
  3590. * @example Info.eras() //=> [ 'BC', 'AD' ]
  3591. * @example Info.eras('long') //=> [ 'Before Christ', 'Anno Domini' ]
  3592. * @example Info.eras('long', { locale: 'fr' }) //=> [ 'avant Jésus-Christ', 'après Jésus-Christ' ]
  3593. * @return {Array}
  3594. */
  3595. static eras(length = "short", {
  3596. locale = null
  3597. } = {}) {
  3598. return Locale.create(locale, null, "gregory").eras(length);
  3599. }
  3600. /**
  3601. * Return the set of available features in this environment.
  3602. * Some features of Luxon are not available in all environments. For example, on older browsers, relative time formatting support is not available. Use this function to figure out if that's the case.
  3603. * Keys:
  3604. * * `relative`: whether this environment supports relative time formatting
  3605. * @example Info.features() //=> { relative: false }
  3606. * @return {Object}
  3607. */
  3608. static features() {
  3609. return {
  3610. relative: hasRelative()
  3611. };
  3612. }
  3613. }
  3614. function dayDiff(earlier, later) {
  3615. const utcDayStart = dt => dt.toUTC(0, {
  3616. keepLocalTime: true
  3617. }).startOf("day").valueOf(),
  3618. ms = utcDayStart(later) - utcDayStart(earlier);
  3619. return Math.floor(Duration.fromMillis(ms).as("days"));
  3620. }
  3621. function highOrderDiffs(cursor, later, units) {
  3622. const differs = [["years", (a, b) => b.year - a.year], ["quarters", (a, b) => b.quarter - a.quarter + (b.year - a.year) * 4], ["months", (a, b) => b.month - a.month + (b.year - a.year) * 12], ["weeks", (a, b) => {
  3623. const days = dayDiff(a, b);
  3624. return (days - days % 7) / 7;
  3625. }], ["days", dayDiff]];
  3626. const results = {};
  3627. let lowestOrder, highWater;
  3628. for (const [unit, differ] of differs) {
  3629. if (units.indexOf(unit) >= 0) {
  3630. lowestOrder = unit;
  3631. let delta = differ(cursor, later);
  3632. highWater = cursor.plus({
  3633. [unit]: delta
  3634. });
  3635. if (highWater > later) {
  3636. cursor = cursor.plus({
  3637. [unit]: delta - 1
  3638. });
  3639. delta -= 1;
  3640. } else {
  3641. cursor = highWater;
  3642. }
  3643. results[unit] = delta;
  3644. }
  3645. }
  3646. return [cursor, results, highWater, lowestOrder];
  3647. }
  3648. function diff (earlier, later, units, opts) {
  3649. let [cursor, results, highWater, lowestOrder] = highOrderDiffs(earlier, later, units);
  3650. const remainingMillis = later - cursor;
  3651. const lowerOrderUnits = units.filter(u => ["hours", "minutes", "seconds", "milliseconds"].indexOf(u) >= 0);
  3652. if (lowerOrderUnits.length === 0) {
  3653. if (highWater < later) {
  3654. highWater = cursor.plus({
  3655. [lowestOrder]: 1
  3656. });
  3657. }
  3658. if (highWater !== cursor) {
  3659. results[lowestOrder] = (results[lowestOrder] || 0) + remainingMillis / (highWater - cursor);
  3660. }
  3661. }
  3662. const duration = Duration.fromObject(results, opts);
  3663. if (lowerOrderUnits.length > 0) {
  3664. return Duration.fromMillis(remainingMillis, opts).shiftTo(...lowerOrderUnits).plus(duration);
  3665. } else {
  3666. return duration;
  3667. }
  3668. }
  3669. const numberingSystems = {
  3670. arab: "[\u0660-\u0669]",
  3671. arabext: "[\u06F0-\u06F9]",
  3672. bali: "[\u1B50-\u1B59]",
  3673. beng: "[\u09E6-\u09EF]",
  3674. deva: "[\u0966-\u096F]",
  3675. fullwide: "[\uFF10-\uFF19]",
  3676. gujr: "[\u0AE6-\u0AEF]",
  3677. hanidec: "[〇|一|二|三|四|五|六|七|八|九]",
  3678. khmr: "[\u17E0-\u17E9]",
  3679. knda: "[\u0CE6-\u0CEF]",
  3680. laoo: "[\u0ED0-\u0ED9]",
  3681. limb: "[\u1946-\u194F]",
  3682. mlym: "[\u0D66-\u0D6F]",
  3683. mong: "[\u1810-\u1819]",
  3684. mymr: "[\u1040-\u1049]",
  3685. orya: "[\u0B66-\u0B6F]",
  3686. tamldec: "[\u0BE6-\u0BEF]",
  3687. telu: "[\u0C66-\u0C6F]",
  3688. thai: "[\u0E50-\u0E59]",
  3689. tibt: "[\u0F20-\u0F29]",
  3690. latn: "\\d"
  3691. };
  3692. const numberingSystemsUTF16 = {
  3693. arab: [1632, 1641],
  3694. arabext: [1776, 1785],
  3695. bali: [6992, 7001],
  3696. beng: [2534, 2543],
  3697. deva: [2406, 2415],
  3698. fullwide: [65296, 65303],
  3699. gujr: [2790, 2799],
  3700. khmr: [6112, 6121],
  3701. knda: [3302, 3311],
  3702. laoo: [3792, 3801],
  3703. limb: [6470, 6479],
  3704. mlym: [3430, 3439],
  3705. mong: [6160, 6169],
  3706. mymr: [4160, 4169],
  3707. orya: [2918, 2927],
  3708. tamldec: [3046, 3055],
  3709. telu: [3174, 3183],
  3710. thai: [3664, 3673],
  3711. tibt: [3872, 3881]
  3712. };
  3713. const hanidecChars = numberingSystems.hanidec.replace(/[\[|\]]/g, "").split("");
  3714. function parseDigits(str) {
  3715. let value = parseInt(str, 10);
  3716. if (isNaN(value)) {
  3717. value = "";
  3718. for (let i = 0; i < str.length; i++) {
  3719. const code = str.charCodeAt(i);
  3720. if (str[i].search(numberingSystems.hanidec) !== -1) {
  3721. value += hanidecChars.indexOf(str[i]);
  3722. } else {
  3723. for (const key in numberingSystemsUTF16) {
  3724. const [min, max] = numberingSystemsUTF16[key];
  3725. if (code >= min && code <= max) {
  3726. value += code - min;
  3727. }
  3728. }
  3729. }
  3730. }
  3731. return parseInt(value, 10);
  3732. } else {
  3733. return value;
  3734. }
  3735. }
  3736. function digitRegex({
  3737. numberingSystem
  3738. }, append = "") {
  3739. return new RegExp(`${numberingSystems[numberingSystem || "latn"]}${append}`);
  3740. }
  3741. const MISSING_FTP = "missing Intl.DateTimeFormat.formatToParts support";
  3742. function intUnit(regex, post = i => i) {
  3743. return {
  3744. regex,
  3745. deser: ([s]) => post(parseDigits(s))
  3746. };
  3747. }
  3748. const NBSP = String.fromCharCode(160);
  3749. const spaceOrNBSP = `[ ${NBSP}]`;
  3750. const spaceOrNBSPRegExp = new RegExp(spaceOrNBSP, "g");
  3751. function fixListRegex(s) {
  3752. // make dots optional and also make them literal
  3753. // make space and non breakable space characters interchangeable
  3754. return s.replace(/\./g, "\\.?").replace(spaceOrNBSPRegExp, spaceOrNBSP);
  3755. }
  3756. function stripInsensitivities(s) {
  3757. return s.replace(/\./g, "") // ignore dots that were made optional
  3758. .replace(spaceOrNBSPRegExp, " ") // interchange space and nbsp
  3759. .toLowerCase();
  3760. }
  3761. function oneOf(strings, startIndex) {
  3762. if (strings === null) {
  3763. return null;
  3764. } else {
  3765. return {
  3766. regex: RegExp(strings.map(fixListRegex).join("|")),
  3767. deser: ([s]) => strings.findIndex(i => stripInsensitivities(s) === stripInsensitivities(i)) + startIndex
  3768. };
  3769. }
  3770. }
  3771. function offset(regex, groups) {
  3772. return {
  3773. regex,
  3774. deser: ([, h, m]) => signedOffset(h, m),
  3775. groups
  3776. };
  3777. }
  3778. function simple(regex) {
  3779. return {
  3780. regex,
  3781. deser: ([s]) => s
  3782. };
  3783. }
  3784. function escapeToken(value) {
  3785. return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
  3786. }
  3787. function unitForToken(token, loc) {
  3788. const one = digitRegex(loc),
  3789. two = digitRegex(loc, "{2}"),
  3790. three = digitRegex(loc, "{3}"),
  3791. four = digitRegex(loc, "{4}"),
  3792. six = digitRegex(loc, "{6}"),
  3793. oneOrTwo = digitRegex(loc, "{1,2}"),
  3794. oneToThree = digitRegex(loc, "{1,3}"),
  3795. oneToSix = digitRegex(loc, "{1,6}"),
  3796. oneToNine = digitRegex(loc, "{1,9}"),
  3797. twoToFour = digitRegex(loc, "{2,4}"),
  3798. fourToSix = digitRegex(loc, "{4,6}"),
  3799. literal = t => ({
  3800. regex: RegExp(escapeToken(t.val)),
  3801. deser: ([s]) => s,
  3802. literal: true
  3803. }),
  3804. unitate = t => {
  3805. if (token.literal) {
  3806. return literal(t);
  3807. }
  3808. switch (t.val) {
  3809. // era
  3810. case "G":
  3811. return oneOf(loc.eras("short", false), 0);
  3812. case "GG":
  3813. return oneOf(loc.eras("long", false), 0);
  3814. // years
  3815. case "y":
  3816. return intUnit(oneToSix);
  3817. case "yy":
  3818. return intUnit(twoToFour, untruncateYear);
  3819. case "yyyy":
  3820. return intUnit(four);
  3821. case "yyyyy":
  3822. return intUnit(fourToSix);
  3823. case "yyyyyy":
  3824. return intUnit(six);
  3825. // months
  3826. case "M":
  3827. return intUnit(oneOrTwo);
  3828. case "MM":
  3829. return intUnit(two);
  3830. case "MMM":
  3831. return oneOf(loc.months("short", true, false), 1);
  3832. case "MMMM":
  3833. return oneOf(loc.months("long", true, false), 1);
  3834. case "L":
  3835. return intUnit(oneOrTwo);
  3836. case "LL":
  3837. return intUnit(two);
  3838. case "LLL":
  3839. return oneOf(loc.months("short", false, false), 1);
  3840. case "LLLL":
  3841. return oneOf(loc.months("long", false, false), 1);
  3842. // dates
  3843. case "d":
  3844. return intUnit(oneOrTwo);
  3845. case "dd":
  3846. return intUnit(two);
  3847. // ordinals
  3848. case "o":
  3849. return intUnit(oneToThree);
  3850. case "ooo":
  3851. return intUnit(three);
  3852. // time
  3853. case "HH":
  3854. return intUnit(two);
  3855. case "H":
  3856. return intUnit(oneOrTwo);
  3857. case "hh":
  3858. return intUnit(two);
  3859. case "h":
  3860. return intUnit(oneOrTwo);
  3861. case "mm":
  3862. return intUnit(two);
  3863. case "m":
  3864. return intUnit(oneOrTwo);
  3865. case "q":
  3866. return intUnit(oneOrTwo);
  3867. case "qq":
  3868. return intUnit(two);
  3869. case "s":
  3870. return intUnit(oneOrTwo);
  3871. case "ss":
  3872. return intUnit(two);
  3873. case "S":
  3874. return intUnit(oneToThree);
  3875. case "SSS":
  3876. return intUnit(three);
  3877. case "u":
  3878. return simple(oneToNine);
  3879. case "uu":
  3880. return simple(oneOrTwo);
  3881. case "uuu":
  3882. return intUnit(one);
  3883. // meridiem
  3884. case "a":
  3885. return oneOf(loc.meridiems(), 0);
  3886. // weekYear (k)
  3887. case "kkkk":
  3888. return intUnit(four);
  3889. case "kk":
  3890. return intUnit(twoToFour, untruncateYear);
  3891. // weekNumber (W)
  3892. case "W":
  3893. return intUnit(oneOrTwo);
  3894. case "WW":
  3895. return intUnit(two);
  3896. // weekdays
  3897. case "E":
  3898. case "c":
  3899. return intUnit(one);
  3900. case "EEE":
  3901. return oneOf(loc.weekdays("short", false, false), 1);
  3902. case "EEEE":
  3903. return oneOf(loc.weekdays("long", false, false), 1);
  3904. case "ccc":
  3905. return oneOf(loc.weekdays("short", true, false), 1);
  3906. case "cccc":
  3907. return oneOf(loc.weekdays("long", true, false), 1);
  3908. // offset/zone
  3909. case "Z":
  3910. case "ZZ":
  3911. return offset(new RegExp(`([+-]${oneOrTwo.source})(?::(${two.source}))?`), 2);
  3912. case "ZZZ":
  3913. return offset(new RegExp(`([+-]${oneOrTwo.source})(${two.source})?`), 2);
  3914. // we don't support ZZZZ (PST) or ZZZZZ (Pacific Standard Time) in parsing
  3915. // because we don't have any way to figure out what they are
  3916. case "z":
  3917. return simple(/[a-z_+-/]{1,256}?/i);
  3918. default:
  3919. return literal(t);
  3920. }
  3921. };
  3922. const unit = unitate(token) || {
  3923. invalidReason: MISSING_FTP
  3924. };
  3925. unit.token = token;
  3926. return unit;
  3927. }
  3928. const partTypeStyleToTokenVal = {
  3929. year: {
  3930. "2-digit": "yy",
  3931. numeric: "yyyyy"
  3932. },
  3933. month: {
  3934. numeric: "M",
  3935. "2-digit": "MM",
  3936. short: "MMM",
  3937. long: "MMMM"
  3938. },
  3939. day: {
  3940. numeric: "d",
  3941. "2-digit": "dd"
  3942. },
  3943. weekday: {
  3944. short: "EEE",
  3945. long: "EEEE"
  3946. },
  3947. dayperiod: "a",
  3948. dayPeriod: "a",
  3949. hour: {
  3950. numeric: "h",
  3951. "2-digit": "hh"
  3952. },
  3953. minute: {
  3954. numeric: "m",
  3955. "2-digit": "mm"
  3956. },
  3957. second: {
  3958. numeric: "s",
  3959. "2-digit": "ss"
  3960. },
  3961. timeZoneName: {
  3962. long: "ZZZZZ",
  3963. short: "ZZZ"
  3964. }
  3965. };
  3966. function tokenForPart(part, locale, formatOpts) {
  3967. const {
  3968. type,
  3969. value
  3970. } = part;
  3971. if (type === "literal") {
  3972. return {
  3973. literal: true,
  3974. val: value
  3975. };
  3976. }
  3977. const style = formatOpts[type];
  3978. let val = partTypeStyleToTokenVal[type];
  3979. if (typeof val === "object") {
  3980. val = val[style];
  3981. }
  3982. if (val) {
  3983. return {
  3984. literal: false,
  3985. val
  3986. };
  3987. }
  3988. return undefined;
  3989. }
  3990. function buildRegex(units) {
  3991. const re = units.map(u => u.regex).reduce((f, r) => `${f}(${r.source})`, "");
  3992. return [`^${re}$`, units];
  3993. }
  3994. function match(input, regex, handlers) {
  3995. const matches = input.match(regex);
  3996. if (matches) {
  3997. const all = {};
  3998. let matchIndex = 1;
  3999. for (const i in handlers) {
  4000. if (hasOwnProperty(handlers, i)) {
  4001. const h = handlers[i],
  4002. groups = h.groups ? h.groups + 1 : 1;
  4003. if (!h.literal && h.token) {
  4004. all[h.token.val[0]] = h.deser(matches.slice(matchIndex, matchIndex + groups));
  4005. }
  4006. matchIndex += groups;
  4007. }
  4008. }
  4009. return [matches, all];
  4010. } else {
  4011. return [matches, {}];
  4012. }
  4013. }
  4014. function dateTimeFromMatches(matches) {
  4015. const toField = token => {
  4016. switch (token) {
  4017. case "S":
  4018. return "millisecond";
  4019. case "s":
  4020. return "second";
  4021. case "m":
  4022. return "minute";
  4023. case "h":
  4024. case "H":
  4025. return "hour";
  4026. case "d":
  4027. return "day";
  4028. case "o":
  4029. return "ordinal";
  4030. case "L":
  4031. case "M":
  4032. return "month";
  4033. case "y":
  4034. return "year";
  4035. case "E":
  4036. case "c":
  4037. return "weekday";
  4038. case "W":
  4039. return "weekNumber";
  4040. case "k":
  4041. return "weekYear";
  4042. case "q":
  4043. return "quarter";
  4044. default:
  4045. return null;
  4046. }
  4047. };
  4048. let zone = null;
  4049. let specificOffset;
  4050. if (!isUndefined(matches.z)) {
  4051. zone = IANAZone.create(matches.z);
  4052. }
  4053. if (!isUndefined(matches.Z)) {
  4054. if (!zone) {
  4055. zone = new FixedOffsetZone(matches.Z);
  4056. }
  4057. specificOffset = matches.Z;
  4058. }
  4059. if (!isUndefined(matches.q)) {
  4060. matches.M = (matches.q - 1) * 3 + 1;
  4061. }
  4062. if (!isUndefined(matches.h)) {
  4063. if (matches.h < 12 && matches.a === 1) {
  4064. matches.h += 12;
  4065. } else if (matches.h === 12 && matches.a === 0) {
  4066. matches.h = 0;
  4067. }
  4068. }
  4069. if (matches.G === 0 && matches.y) {
  4070. matches.y = -matches.y;
  4071. }
  4072. if (!isUndefined(matches.u)) {
  4073. matches.S = parseMillis(matches.u);
  4074. }
  4075. const vals = Object.keys(matches).reduce((r, k) => {
  4076. const f = toField(k);
  4077. if (f) {
  4078. r[f] = matches[k];
  4079. }
  4080. return r;
  4081. }, {});
  4082. return [vals, zone, specificOffset];
  4083. }
  4084. let dummyDateTimeCache = null;
  4085. function getDummyDateTime() {
  4086. if (!dummyDateTimeCache) {
  4087. dummyDateTimeCache = DateTime.fromMillis(1555555555555);
  4088. }
  4089. return dummyDateTimeCache;
  4090. }
  4091. function maybeExpandMacroToken(token, locale) {
  4092. if (token.literal) {
  4093. return token;
  4094. }
  4095. const formatOpts = Formatter.macroTokenToFormatOpts(token.val);
  4096. const tokens = formatOptsToTokens(formatOpts, locale);
  4097. if (tokens == null || tokens.includes(undefined)) {
  4098. return token;
  4099. }
  4100. return tokens;
  4101. }
  4102. function expandMacroTokens(tokens, locale) {
  4103. return Array.prototype.concat(...tokens.map(t => maybeExpandMacroToken(t, locale)));
  4104. }
  4105. /**
  4106. * @private
  4107. */
  4108. function explainFromTokens(locale, input, format) {
  4109. const tokens = expandMacroTokens(Formatter.parseFormat(format), locale),
  4110. units = tokens.map(t => unitForToken(t, locale)),
  4111. disqualifyingUnit = units.find(t => t.invalidReason);
  4112. if (disqualifyingUnit) {
  4113. return {
  4114. input,
  4115. tokens,
  4116. invalidReason: disqualifyingUnit.invalidReason
  4117. };
  4118. } else {
  4119. const [regexString, handlers] = buildRegex(units),
  4120. regex = RegExp(regexString, "i"),
  4121. [rawMatches, matches] = match(input, regex, handlers),
  4122. [result, zone, specificOffset] = matches ? dateTimeFromMatches(matches) : [null, null, undefined];
  4123. if (hasOwnProperty(matches, "a") && hasOwnProperty(matches, "H")) {
  4124. throw new ConflictingSpecificationError("Can't include meridiem when specifying 24-hour format");
  4125. }
  4126. return {
  4127. input,
  4128. tokens,
  4129. regex,
  4130. rawMatches,
  4131. matches,
  4132. result,
  4133. zone,
  4134. specificOffset
  4135. };
  4136. }
  4137. }
  4138. function parseFromTokens(locale, input, format) {
  4139. const {
  4140. result,
  4141. zone,
  4142. specificOffset,
  4143. invalidReason
  4144. } = explainFromTokens(locale, input, format);
  4145. return [result, zone, specificOffset, invalidReason];
  4146. }
  4147. function formatOptsToTokens(formatOpts, locale) {
  4148. if (!formatOpts) {
  4149. return null;
  4150. }
  4151. const formatter = Formatter.create(locale, formatOpts);
  4152. const parts = formatter.formatDateTimeParts(getDummyDateTime());
  4153. return parts.map(p => tokenForPart(p, locale, formatOpts));
  4154. }
  4155. const nonLeapLadder = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334],
  4156. leapLadder = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335];
  4157. function unitOutOfRange(unit, value) {
  4158. return new Invalid("unit out of range", `you specified ${value} (of type ${typeof value}) as a ${unit}, which is invalid`);
  4159. }
  4160. function dayOfWeek(year, month, day) {
  4161. const d = new Date(Date.UTC(year, month - 1, day));
  4162. if (year < 100 && year >= 0) {
  4163. d.setUTCFullYear(d.getUTCFullYear() - 1900);
  4164. }
  4165. const js = d.getUTCDay();
  4166. return js === 0 ? 7 : js;
  4167. }
  4168. function computeOrdinal(year, month, day) {
  4169. return day + (isLeapYear(year) ? leapLadder : nonLeapLadder)[month - 1];
  4170. }
  4171. function uncomputeOrdinal(year, ordinal) {
  4172. const table = isLeapYear(year) ? leapLadder : nonLeapLadder,
  4173. month0 = table.findIndex(i => i < ordinal),
  4174. day = ordinal - table[month0];
  4175. return {
  4176. month: month0 + 1,
  4177. day
  4178. };
  4179. }
  4180. /**
  4181. * @private
  4182. */
  4183. function gregorianToWeek(gregObj) {
  4184. const {
  4185. year,
  4186. month,
  4187. day
  4188. } = gregObj,
  4189. ordinal = computeOrdinal(year, month, day),
  4190. weekday = dayOfWeek(year, month, day);
  4191. let weekNumber = Math.floor((ordinal - weekday + 10) / 7),
  4192. weekYear;
  4193. if (weekNumber < 1) {
  4194. weekYear = year - 1;
  4195. weekNumber = weeksInWeekYear(weekYear);
  4196. } else if (weekNumber > weeksInWeekYear(year)) {
  4197. weekYear = year + 1;
  4198. weekNumber = 1;
  4199. } else {
  4200. weekYear = year;
  4201. }
  4202. return {
  4203. weekYear,
  4204. weekNumber,
  4205. weekday,
  4206. ...timeObject(gregObj)
  4207. };
  4208. }
  4209. function weekToGregorian(weekData) {
  4210. const {
  4211. weekYear,
  4212. weekNumber,
  4213. weekday
  4214. } = weekData,
  4215. weekdayOfJan4 = dayOfWeek(weekYear, 1, 4),
  4216. yearInDays = daysInYear(weekYear);
  4217. let ordinal = weekNumber * 7 + weekday - weekdayOfJan4 - 3,
  4218. year;
  4219. if (ordinal < 1) {
  4220. year = weekYear - 1;
  4221. ordinal += daysInYear(year);
  4222. } else if (ordinal > yearInDays) {
  4223. year = weekYear + 1;
  4224. ordinal -= daysInYear(weekYear);
  4225. } else {
  4226. year = weekYear;
  4227. }
  4228. const {
  4229. month,
  4230. day
  4231. } = uncomputeOrdinal(year, ordinal);
  4232. return {
  4233. year,
  4234. month,
  4235. day,
  4236. ...timeObject(weekData)
  4237. };
  4238. }
  4239. function gregorianToOrdinal(gregData) {
  4240. const {
  4241. year,
  4242. month,
  4243. day
  4244. } = gregData;
  4245. const ordinal = computeOrdinal(year, month, day);
  4246. return {
  4247. year,
  4248. ordinal,
  4249. ...timeObject(gregData)
  4250. };
  4251. }
  4252. function ordinalToGregorian(ordinalData) {
  4253. const {
  4254. year,
  4255. ordinal
  4256. } = ordinalData;
  4257. const {
  4258. month,
  4259. day
  4260. } = uncomputeOrdinal(year, ordinal);
  4261. return {
  4262. year,
  4263. month,
  4264. day,
  4265. ...timeObject(ordinalData)
  4266. };
  4267. }
  4268. function hasInvalidWeekData(obj) {
  4269. const validYear = isInteger(obj.weekYear),
  4270. validWeek = integerBetween(obj.weekNumber, 1, weeksInWeekYear(obj.weekYear)),
  4271. validWeekday = integerBetween(obj.weekday, 1, 7);
  4272. if (!validYear) {
  4273. return unitOutOfRange("weekYear", obj.weekYear);
  4274. } else if (!validWeek) {
  4275. return unitOutOfRange("week", obj.week);
  4276. } else if (!validWeekday) {
  4277. return unitOutOfRange("weekday", obj.weekday);
  4278. } else return false;
  4279. }
  4280. function hasInvalidOrdinalData(obj) {
  4281. const validYear = isInteger(obj.year),
  4282. validOrdinal = integerBetween(obj.ordinal, 1, daysInYear(obj.year));
  4283. if (!validYear) {
  4284. return unitOutOfRange("year", obj.year);
  4285. } else if (!validOrdinal) {
  4286. return unitOutOfRange("ordinal", obj.ordinal);
  4287. } else return false;
  4288. }
  4289. function hasInvalidGregorianData(obj) {
  4290. const validYear = isInteger(obj.year),
  4291. validMonth = integerBetween(obj.month, 1, 12),
  4292. validDay = integerBetween(obj.day, 1, daysInMonth(obj.year, obj.month));
  4293. if (!validYear) {
  4294. return unitOutOfRange("year", obj.year);
  4295. } else if (!validMonth) {
  4296. return unitOutOfRange("month", obj.month);
  4297. } else if (!validDay) {
  4298. return unitOutOfRange("day", obj.day);
  4299. } else return false;
  4300. }
  4301. function hasInvalidTimeData(obj) {
  4302. const {
  4303. hour,
  4304. minute,
  4305. second,
  4306. millisecond
  4307. } = obj;
  4308. const validHour = integerBetween(hour, 0, 23) || hour === 24 && minute === 0 && second === 0 && millisecond === 0,
  4309. validMinute = integerBetween(minute, 0, 59),
  4310. validSecond = integerBetween(second, 0, 59),
  4311. validMillisecond = integerBetween(millisecond, 0, 999);
  4312. if (!validHour) {
  4313. return unitOutOfRange("hour", hour);
  4314. } else if (!validMinute) {
  4315. return unitOutOfRange("minute", minute);
  4316. } else if (!validSecond) {
  4317. return unitOutOfRange("second", second);
  4318. } else if (!validMillisecond) {
  4319. return unitOutOfRange("millisecond", millisecond);
  4320. } else return false;
  4321. }
  4322. const INVALID = "Invalid DateTime";
  4323. const MAX_DATE = 8.64e15;
  4324. function unsupportedZone(zone) {
  4325. return new Invalid("unsupported zone", `the zone "${zone.name}" is not supported`);
  4326. } // we cache week data on the DT object and this intermediates the cache
  4327. function possiblyCachedWeekData(dt) {
  4328. if (dt.weekData === null) {
  4329. dt.weekData = gregorianToWeek(dt.c);
  4330. }
  4331. return dt.weekData;
  4332. } // clone really means, "make a new object with these modifications". all "setters" really use this
  4333. // to create a new object while only changing some of the properties
  4334. function clone(inst, alts) {
  4335. const current = {
  4336. ts: inst.ts,
  4337. zone: inst.zone,
  4338. c: inst.c,
  4339. o: inst.o,
  4340. loc: inst.loc,
  4341. invalid: inst.invalid
  4342. };
  4343. return new DateTime({ ...current,
  4344. ...alts,
  4345. old: current
  4346. });
  4347. } // find the right offset a given local time. The o input is our guess, which determines which
  4348. // offset we'll pick in ambiguous cases (e.g. there are two 3 AMs b/c Fallback DST)
  4349. function fixOffset(localTS, o, tz) {
  4350. // Our UTC time is just a guess because our offset is just a guess
  4351. let utcGuess = localTS - o * 60 * 1000; // Test whether the zone matches the offset for this ts
  4352. const o2 = tz.offset(utcGuess); // If so, offset didn't change and we're done
  4353. if (o === o2) {
  4354. return [utcGuess, o];
  4355. } // If not, change the ts by the difference in the offset
  4356. utcGuess -= (o2 - o) * 60 * 1000; // If that gives us the local time we want, we're done
  4357. const o3 = tz.offset(utcGuess);
  4358. if (o2 === o3) {
  4359. return [utcGuess, o2];
  4360. } // If it's different, we're in a hole time. The offset has changed, but the we don't adjust the time
  4361. return [localTS - Math.min(o2, o3) * 60 * 1000, Math.max(o2, o3)];
  4362. } // convert an epoch timestamp into a calendar object with the given offset
  4363. function tsToObj(ts, offset) {
  4364. ts += offset * 60 * 1000;
  4365. const d = new Date(ts);
  4366. return {
  4367. year: d.getUTCFullYear(),
  4368. month: d.getUTCMonth() + 1,
  4369. day: d.getUTCDate(),
  4370. hour: d.getUTCHours(),
  4371. minute: d.getUTCMinutes(),
  4372. second: d.getUTCSeconds(),
  4373. millisecond: d.getUTCMilliseconds()
  4374. };
  4375. } // convert a calendar object to a epoch timestamp
  4376. function objToTS(obj, offset, zone) {
  4377. return fixOffset(objToLocalTS(obj), offset, zone);
  4378. } // create a new DT instance by adding a duration, adjusting for DSTs
  4379. function adjustTime(inst, dur) {
  4380. const oPre = inst.o,
  4381. year = inst.c.year + Math.trunc(dur.years),
  4382. month = inst.c.month + Math.trunc(dur.months) + Math.trunc(dur.quarters) * 3,
  4383. c = { ...inst.c,
  4384. year,
  4385. month,
  4386. day: Math.min(inst.c.day, daysInMonth(year, month)) + Math.trunc(dur.days) + Math.trunc(dur.weeks) * 7
  4387. },
  4388. millisToAdd = Duration.fromObject({
  4389. years: dur.years - Math.trunc(dur.years),
  4390. quarters: dur.quarters - Math.trunc(dur.quarters),
  4391. months: dur.months - Math.trunc(dur.months),
  4392. weeks: dur.weeks - Math.trunc(dur.weeks),
  4393. days: dur.days - Math.trunc(dur.days),
  4394. hours: dur.hours,
  4395. minutes: dur.minutes,
  4396. seconds: dur.seconds,
  4397. milliseconds: dur.milliseconds
  4398. }).as("milliseconds"),
  4399. localTS = objToLocalTS(c);
  4400. let [ts, o] = fixOffset(localTS, oPre, inst.zone);
  4401. if (millisToAdd !== 0) {
  4402. ts += millisToAdd; // that could have changed the offset by going over a DST, but we want to keep the ts the same
  4403. o = inst.zone.offset(ts);
  4404. }
  4405. return {
  4406. ts,
  4407. o
  4408. };
  4409. } // helper useful in turning the results of parsing into real dates
  4410. // by handling the zone options
  4411. function parseDataToDateTime(parsed, parsedZone, opts, format, text, specificOffset) {
  4412. const {
  4413. setZone,
  4414. zone
  4415. } = opts;
  4416. if (parsed && Object.keys(parsed).length !== 0) {
  4417. const interpretationZone = parsedZone || zone,
  4418. inst = DateTime.fromObject(parsed, { ...opts,
  4419. zone: interpretationZone,
  4420. specificOffset
  4421. });
  4422. return setZone ? inst : inst.setZone(zone);
  4423. } else {
  4424. return DateTime.invalid(new Invalid("unparsable", `the input "${text}" can't be parsed as ${format}`));
  4425. }
  4426. } // if you want to output a technical format (e.g. RFC 2822), this helper
  4427. // helps handle the details
  4428. function toTechFormat(dt, format, allowZ = true) {
  4429. return dt.isValid ? Formatter.create(Locale.create("en-US"), {
  4430. allowZ,
  4431. forceSimple: true
  4432. }).formatDateTimeFromString(dt, format) : null;
  4433. }
  4434. function toISODate(o, extended) {
  4435. const longFormat = o.c.year > 9999 || o.c.year < 0;
  4436. let c = "";
  4437. if (longFormat && o.c.year >= 0) c += "+";
  4438. c += padStart(o.c.year, longFormat ? 6 : 4);
  4439. if (extended) {
  4440. c += "-";
  4441. c += padStart(o.c.month);
  4442. c += "-";
  4443. c += padStart(o.c.day);
  4444. } else {
  4445. c += padStart(o.c.month);
  4446. c += padStart(o.c.day);
  4447. }
  4448. return c;
  4449. }
  4450. function toISOTime(o, extended, suppressSeconds, suppressMilliseconds, includeOffset, extendedZone) {
  4451. let c = padStart(o.c.hour);
  4452. if (extended) {
  4453. c += ":";
  4454. c += padStart(o.c.minute);
  4455. if (o.c.second !== 0 || !suppressSeconds) {
  4456. c += ":";
  4457. }
  4458. } else {
  4459. c += padStart(o.c.minute);
  4460. }
  4461. if (o.c.second !== 0 || !suppressSeconds) {
  4462. c += padStart(o.c.second);
  4463. if (o.c.millisecond !== 0 || !suppressMilliseconds) {
  4464. c += ".";
  4465. c += padStart(o.c.millisecond, 3);
  4466. }
  4467. }
  4468. if (includeOffset) {
  4469. if (o.isOffsetFixed && o.offset === 0 && !extendedZone) {
  4470. c += "Z";
  4471. } else if (o.o < 0) {
  4472. c += "-";
  4473. c += padStart(Math.trunc(-o.o / 60));
  4474. c += ":";
  4475. c += padStart(Math.trunc(-o.o % 60));
  4476. } else {
  4477. c += "+";
  4478. c += padStart(Math.trunc(o.o / 60));
  4479. c += ":";
  4480. c += padStart(Math.trunc(o.o % 60));
  4481. }
  4482. }
  4483. if (extendedZone) {
  4484. c += "[" + o.zone.ianaName + "]";
  4485. }
  4486. return c;
  4487. } // defaults for unspecified units in the supported calendars
  4488. const defaultUnitValues = {
  4489. month: 1,
  4490. day: 1,
  4491. hour: 0,
  4492. minute: 0,
  4493. second: 0,
  4494. millisecond: 0
  4495. },
  4496. defaultWeekUnitValues = {
  4497. weekNumber: 1,
  4498. weekday: 1,
  4499. hour: 0,
  4500. minute: 0,
  4501. second: 0,
  4502. millisecond: 0
  4503. },
  4504. defaultOrdinalUnitValues = {
  4505. ordinal: 1,
  4506. hour: 0,
  4507. minute: 0,
  4508. second: 0,
  4509. millisecond: 0
  4510. }; // Units in the supported calendars, sorted by bigness
  4511. const orderedUnits = ["year", "month", "day", "hour", "minute", "second", "millisecond"],
  4512. orderedWeekUnits = ["weekYear", "weekNumber", "weekday", "hour", "minute", "second", "millisecond"],
  4513. orderedOrdinalUnits = ["year", "ordinal", "hour", "minute", "second", "millisecond"]; // standardize case and plurality in units
  4514. function normalizeUnit(unit) {
  4515. const normalized = {
  4516. year: "year",
  4517. years: "year",
  4518. month: "month",
  4519. months: "month",
  4520. day: "day",
  4521. days: "day",
  4522. hour: "hour",
  4523. hours: "hour",
  4524. minute: "minute",
  4525. minutes: "minute",
  4526. quarter: "quarter",
  4527. quarters: "quarter",
  4528. second: "second",
  4529. seconds: "second",
  4530. millisecond: "millisecond",
  4531. milliseconds: "millisecond",
  4532. weekday: "weekday",
  4533. weekdays: "weekday",
  4534. weeknumber: "weekNumber",
  4535. weeksnumber: "weekNumber",
  4536. weeknumbers: "weekNumber",
  4537. weekyear: "weekYear",
  4538. weekyears: "weekYear",
  4539. ordinal: "ordinal"
  4540. }[unit.toLowerCase()];
  4541. if (!normalized) throw new InvalidUnitError(unit);
  4542. return normalized;
  4543. } // this is a dumbed down version of fromObject() that runs about 60% faster
  4544. // but doesn't do any validation, makes a bunch of assumptions about what units
  4545. // are present, and so on.
  4546. function quickDT(obj, opts) {
  4547. const zone = normalizeZone(opts.zone, Settings.defaultZone),
  4548. loc = Locale.fromObject(opts),
  4549. tsNow = Settings.now();
  4550. let ts, o; // assume we have the higher-order units
  4551. if (!isUndefined(obj.year)) {
  4552. for (const u of orderedUnits) {
  4553. if (isUndefined(obj[u])) {
  4554. obj[u] = defaultUnitValues[u];
  4555. }
  4556. }
  4557. const invalid = hasInvalidGregorianData(obj) || hasInvalidTimeData(obj);
  4558. if (invalid) {
  4559. return DateTime.invalid(invalid);
  4560. }
  4561. const offsetProvis = zone.offset(tsNow);
  4562. [ts, o] = objToTS(obj, offsetProvis, zone);
  4563. } else {
  4564. ts = tsNow;
  4565. }
  4566. return new DateTime({
  4567. ts,
  4568. zone,
  4569. loc,
  4570. o
  4571. });
  4572. }
  4573. function diffRelative(start, end, opts) {
  4574. const round = isUndefined(opts.round) ? true : opts.round,
  4575. format = (c, unit) => {
  4576. c = roundTo(c, round || opts.calendary ? 0 : 2, true);
  4577. const formatter = end.loc.clone(opts).relFormatter(opts);
  4578. return formatter.format(c, unit);
  4579. },
  4580. differ = unit => {
  4581. if (opts.calendary) {
  4582. if (!end.hasSame(start, unit)) {
  4583. return end.startOf(unit).diff(start.startOf(unit), unit).get(unit);
  4584. } else return 0;
  4585. } else {
  4586. return end.diff(start, unit).get(unit);
  4587. }
  4588. };
  4589. if (opts.unit) {
  4590. return format(differ(opts.unit), opts.unit);
  4591. }
  4592. for (const unit of opts.units) {
  4593. const count = differ(unit);
  4594. if (Math.abs(count) >= 1) {
  4595. return format(count, unit);
  4596. }
  4597. }
  4598. return format(start > end ? -0 : 0, opts.units[opts.units.length - 1]);
  4599. }
  4600. function lastOpts(argList) {
  4601. let opts = {},
  4602. args;
  4603. if (argList.length > 0 && typeof argList[argList.length - 1] === "object") {
  4604. opts = argList[argList.length - 1];
  4605. args = Array.from(argList).slice(0, argList.length - 1);
  4606. } else {
  4607. args = Array.from(argList);
  4608. }
  4609. return [opts, args];
  4610. }
  4611. /**
  4612. * A DateTime is an immutable data structure representing a specific date and time and accompanying methods. It contains class and instance methods for creating, parsing, interrogating, transforming, and formatting them.
  4613. *
  4614. * A DateTime comprises of:
  4615. * * A timestamp. Each DateTime instance refers to a specific millisecond of the Unix epoch.
  4616. * * A time zone. Each instance is considered in the context of a specific zone (by default the local system's zone).
  4617. * * Configuration properties that effect how output strings are formatted, such as `locale`, `numberingSystem`, and `outputCalendar`.
  4618. *
  4619. * Here is a brief overview of the most commonly used functionality it provides:
  4620. *
  4621. * * **Creation**: To create a DateTime from its components, use one of its factory class methods: {@link DateTime.local}, {@link DateTime.utc}, and (most flexibly) {@link DateTime.fromObject}. To create one from a standard string format, use {@link DateTime.fromISO}, {@link DateTime.fromHTTP}, and {@link DateTime.fromRFC2822}. To create one from a custom string format, use {@link DateTime.fromFormat}. To create one from a native JS date, use {@link DateTime.fromJSDate}.
  4622. * * **Gregorian calendar and time**: To examine the Gregorian properties of a DateTime individually (i.e as opposed to collectively through {@link DateTime#toObject}), use the {@link DateTime#year}, {@link DateTime#month},
  4623. * {@link DateTime#day}, {@link DateTime#hour}, {@link DateTime#minute}, {@link DateTime#second}, {@link DateTime#millisecond} accessors.
  4624. * * **Week calendar**: For ISO week calendar attributes, see the {@link DateTime#weekYear}, {@link DateTime#weekNumber}, and {@link DateTime#weekday} accessors.
  4625. * * **Configuration** See the {@link DateTime#locale} and {@link DateTime#numberingSystem} accessors.
  4626. * * **Transformation**: To transform the DateTime into other DateTimes, use {@link DateTime#set}, {@link DateTime#reconfigure}, {@link DateTime#setZone}, {@link DateTime#setLocale}, {@link DateTime.plus}, {@link DateTime#minus}, {@link DateTime#endOf}, {@link DateTime#startOf}, {@link DateTime#toUTC}, and {@link DateTime#toLocal}.
  4627. * * **Output**: To convert the DateTime to other representations, use the {@link DateTime#toRelative}, {@link DateTime#toRelativeCalendar}, {@link DateTime#toJSON}, {@link DateTime#toISO}, {@link DateTime#toHTTP}, {@link DateTime#toObject}, {@link DateTime#toRFC2822}, {@link DateTime#toString}, {@link DateTime#toLocaleString}, {@link DateTime#toFormat}, {@link DateTime#toMillis} and {@link DateTime#toJSDate}.
  4628. *
  4629. * There's plenty others documented below. In addition, for more information on subtler topics like internationalization, time zones, alternative calendars, validity, and so on, see the external documentation.
  4630. */
  4631. class DateTime {
  4632. /**
  4633. * @access private
  4634. */
  4635. constructor(config) {
  4636. const zone = config.zone || Settings.defaultZone;
  4637. let invalid = config.invalid || (Number.isNaN(config.ts) ? new Invalid("invalid input") : null) || (!zone.isValid ? unsupportedZone(zone) : null);
  4638. /**
  4639. * @access private
  4640. */
  4641. this.ts = isUndefined(config.ts) ? Settings.now() : config.ts;
  4642. let c = null,
  4643. o = null;
  4644. if (!invalid) {
  4645. const unchanged = config.old && config.old.ts === this.ts && config.old.zone.equals(zone);
  4646. if (unchanged) {
  4647. [c, o] = [config.old.c, config.old.o];
  4648. } else {
  4649. const ot = zone.offset(this.ts);
  4650. c = tsToObj(this.ts, ot);
  4651. invalid = Number.isNaN(c.year) ? new Invalid("invalid input") : null;
  4652. c = invalid ? null : c;
  4653. o = invalid ? null : ot;
  4654. }
  4655. }
  4656. /**
  4657. * @access private
  4658. */
  4659. this._zone = zone;
  4660. /**
  4661. * @access private
  4662. */
  4663. this.loc = config.loc || Locale.create();
  4664. /**
  4665. * @access private
  4666. */
  4667. this.invalid = invalid;
  4668. /**
  4669. * @access private
  4670. */
  4671. this.weekData = null;
  4672. /**
  4673. * @access private
  4674. */
  4675. this.c = c;
  4676. /**
  4677. * @access private
  4678. */
  4679. this.o = o;
  4680. /**
  4681. * @access private
  4682. */
  4683. this.isLuxonDateTime = true;
  4684. } // CONSTRUCT
  4685. /**
  4686. * Create a DateTime for the current instant, in the system's time zone.
  4687. *
  4688. * Use Settings to override these default values if needed.
  4689. * @example DateTime.now().toISO() //~> now in the ISO format
  4690. * @return {DateTime}
  4691. */
  4692. static now() {
  4693. return new DateTime({});
  4694. }
  4695. /**
  4696. * Create a local DateTime
  4697. * @param {number} [year] - The calendar year. If omitted (as in, call `local()` with no arguments), the current time will be used
  4698. * @param {number} [month=1] - The month, 1-indexed
  4699. * @param {number} [day=1] - The day of the month, 1-indexed
  4700. * @param {number} [hour=0] - The hour of the day, in 24-hour time
  4701. * @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59
  4702. * @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59
  4703. * @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999
  4704. * @example DateTime.local() //~> now
  4705. * @example DateTime.local({ zone: "America/New_York" }) //~> now, in US east coast time
  4706. * @example DateTime.local(2017) //~> 2017-01-01T00:00:00
  4707. * @example DateTime.local(2017, 3) //~> 2017-03-01T00:00:00
  4708. * @example DateTime.local(2017, 3, 12, { locale: "fr" }) //~> 2017-03-12T00:00:00, with a French locale
  4709. * @example DateTime.local(2017, 3, 12, 5) //~> 2017-03-12T05:00:00
  4710. * @example DateTime.local(2017, 3, 12, 5, { zone: "utc" }) //~> 2017-03-12T05:00:00, in UTC
  4711. * @example DateTime.local(2017, 3, 12, 5, 45) //~> 2017-03-12T05:45:00
  4712. * @example DateTime.local(2017, 3, 12, 5, 45, 10) //~> 2017-03-12T05:45:10
  4713. * @example DateTime.local(2017, 3, 12, 5, 45, 10, 765) //~> 2017-03-12T05:45:10.765
  4714. * @return {DateTime}
  4715. */
  4716. static local() {
  4717. const [opts, args] = lastOpts(arguments),
  4718. [year, month, day, hour, minute, second, millisecond] = args;
  4719. return quickDT({
  4720. year,
  4721. month,
  4722. day,
  4723. hour,
  4724. minute,
  4725. second,
  4726. millisecond
  4727. }, opts);
  4728. }
  4729. /**
  4730. * Create a DateTime in UTC
  4731. * @param {number} [year] - The calendar year. If omitted (as in, call `utc()` with no arguments), the current time will be used
  4732. * @param {number} [month=1] - The month, 1-indexed
  4733. * @param {number} [day=1] - The day of the month
  4734. * @param {number} [hour=0] - The hour of the day, in 24-hour time
  4735. * @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59
  4736. * @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59
  4737. * @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999
  4738. * @param {Object} options - configuration options for the DateTime
  4739. * @param {string} [options.locale] - a locale to set on the resulting DateTime instance
  4740. * @param {string} [options.outputCalendar] - the output calendar to set on the resulting DateTime instance
  4741. * @param {string} [options.numberingSystem] - the numbering system to set on the resulting DateTime instance
  4742. * @example DateTime.utc() //~> now
  4743. * @example DateTime.utc(2017) //~> 2017-01-01T00:00:00Z
  4744. * @example DateTime.utc(2017, 3) //~> 2017-03-01T00:00:00Z
  4745. * @example DateTime.utc(2017, 3, 12) //~> 2017-03-12T00:00:00Z
  4746. * @example DateTime.utc(2017, 3, 12, 5) //~> 2017-03-12T05:00:00Z
  4747. * @example DateTime.utc(2017, 3, 12, 5, 45) //~> 2017-03-12T05:45:00Z
  4748. * @example DateTime.utc(2017, 3, 12, 5, 45, { locale: "fr" }) //~> 2017-03-12T05:45:00Z with a French locale
  4749. * @example DateTime.utc(2017, 3, 12, 5, 45, 10) //~> 2017-03-12T05:45:10Z
  4750. * @example DateTime.utc(2017, 3, 12, 5, 45, 10, 765, { locale: "fr" }) //~> 2017-03-12T05:45:10.765Z with a French locale
  4751. * @return {DateTime}
  4752. */
  4753. static utc() {
  4754. const [opts, args] = lastOpts(arguments),
  4755. [year, month, day, hour, minute, second, millisecond] = args;
  4756. opts.zone = FixedOffsetZone.utcInstance;
  4757. return quickDT({
  4758. year,
  4759. month,
  4760. day,
  4761. hour,
  4762. minute,
  4763. second,
  4764. millisecond
  4765. }, opts);
  4766. }
  4767. /**
  4768. * Create a DateTime from a JavaScript Date object. Uses the default zone.
  4769. * @param {Date} date - a JavaScript Date object
  4770. * @param {Object} options - configuration options for the DateTime
  4771. * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into
  4772. * @return {DateTime}
  4773. */
  4774. static fromJSDate(date, options = {}) {
  4775. const ts = isDate(date) ? date.valueOf() : NaN;
  4776. if (Number.isNaN(ts)) {
  4777. return DateTime.invalid("invalid input");
  4778. }
  4779. const zoneToUse = normalizeZone(options.zone, Settings.defaultZone);
  4780. if (!zoneToUse.isValid) {
  4781. return DateTime.invalid(unsupportedZone(zoneToUse));
  4782. }
  4783. return new DateTime({
  4784. ts: ts,
  4785. zone: zoneToUse,
  4786. loc: Locale.fromObject(options)
  4787. });
  4788. }
  4789. /**
  4790. * Create a DateTime from a number of milliseconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone.
  4791. * @param {number} milliseconds - a number of milliseconds since 1970 UTC
  4792. * @param {Object} options - configuration options for the DateTime
  4793. * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into
  4794. * @param {string} [options.locale] - a locale to set on the resulting DateTime instance
  4795. * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance
  4796. * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance
  4797. * @return {DateTime}
  4798. */
  4799. static fromMillis(milliseconds, options = {}) {
  4800. if (!isNumber(milliseconds)) {
  4801. throw new InvalidArgumentError(`fromMillis requires a numerical input, but received a ${typeof milliseconds} with value ${milliseconds}`);
  4802. } else if (milliseconds < -MAX_DATE || milliseconds > MAX_DATE) {
  4803. // this isn't perfect because because we can still end up out of range because of additional shifting, but it's a start
  4804. return DateTime.invalid("Timestamp out of range");
  4805. } else {
  4806. return new DateTime({
  4807. ts: milliseconds,
  4808. zone: normalizeZone(options.zone, Settings.defaultZone),
  4809. loc: Locale.fromObject(options)
  4810. });
  4811. }
  4812. }
  4813. /**
  4814. * Create a DateTime from a number of seconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone.
  4815. * @param {number} seconds - a number of seconds since 1970 UTC
  4816. * @param {Object} options - configuration options for the DateTime
  4817. * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into
  4818. * @param {string} [options.locale] - a locale to set on the resulting DateTime instance
  4819. * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance
  4820. * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance
  4821. * @return {DateTime}
  4822. */
  4823. static fromSeconds(seconds, options = {}) {
  4824. if (!isNumber(seconds)) {
  4825. throw new InvalidArgumentError("fromSeconds requires a numerical input");
  4826. } else {
  4827. return new DateTime({
  4828. ts: seconds * 1000,
  4829. zone: normalizeZone(options.zone, Settings.defaultZone),
  4830. loc: Locale.fromObject(options)
  4831. });
  4832. }
  4833. }
  4834. /**
  4835. * Create a DateTime from a JavaScript object with keys like 'year' and 'hour' with reasonable defaults.
  4836. * @param {Object} obj - the object to create the DateTime from
  4837. * @param {number} obj.year - a year, such as 1987
  4838. * @param {number} obj.month - a month, 1-12
  4839. * @param {number} obj.day - a day of the month, 1-31, depending on the month
  4840. * @param {number} obj.ordinal - day of the year, 1-365 or 366
  4841. * @param {number} obj.weekYear - an ISO week year
  4842. * @param {number} obj.weekNumber - an ISO week number, between 1 and 52 or 53, depending on the year
  4843. * @param {number} obj.weekday - an ISO weekday, 1-7, where 1 is Monday and 7 is Sunday
  4844. * @param {number} obj.hour - hour of the day, 0-23
  4845. * @param {number} obj.minute - minute of the hour, 0-59
  4846. * @param {number} obj.second - second of the minute, 0-59
  4847. * @param {number} obj.millisecond - millisecond of the second, 0-999
  4848. * @param {Object} opts - options for creating this DateTime
  4849. * @param {string|Zone} [opts.zone='local'] - interpret the numbers in the context of a particular zone. Can take any value taken as the first argument to setZone()
  4850. * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance
  4851. * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
  4852. * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance
  4853. * @example DateTime.fromObject({ year: 1982, month: 5, day: 25}).toISODate() //=> '1982-05-25'
  4854. * @example DateTime.fromObject({ year: 1982 }).toISODate() //=> '1982-01-01'
  4855. * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }) //~> today at 10:26:06
  4856. * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'utc' }),
  4857. * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'local' })
  4858. * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'America/New_York' })
  4859. * @example DateTime.fromObject({ weekYear: 2016, weekNumber: 2, weekday: 3 }).toISODate() //=> '2016-01-13'
  4860. * @return {DateTime}
  4861. */
  4862. static fromObject(obj, opts = {}) {
  4863. obj = obj || {};
  4864. const zoneToUse = normalizeZone(opts.zone, Settings.defaultZone);
  4865. if (!zoneToUse.isValid) {
  4866. return DateTime.invalid(unsupportedZone(zoneToUse));
  4867. }
  4868. const tsNow = Settings.now(),
  4869. offsetProvis = !isUndefined(opts.specificOffset) ? opts.specificOffset : zoneToUse.offset(tsNow),
  4870. normalized = normalizeObject(obj, normalizeUnit),
  4871. containsOrdinal = !isUndefined(normalized.ordinal),
  4872. containsGregorYear = !isUndefined(normalized.year),
  4873. containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day),
  4874. containsGregor = containsGregorYear || containsGregorMD,
  4875. definiteWeekDef = normalized.weekYear || normalized.weekNumber,
  4876. loc = Locale.fromObject(opts); // cases:
  4877. // just a weekday -> this week's instance of that weekday, no worries
  4878. // (gregorian data or ordinal) + (weekYear or weekNumber) -> error
  4879. // (gregorian month or day) + ordinal -> error
  4880. // otherwise just use weeks or ordinals or gregorian, depending on what's specified
  4881. if ((containsGregor || containsOrdinal) && definiteWeekDef) {
  4882. throw new ConflictingSpecificationError("Can't mix weekYear/weekNumber units with year/month/day or ordinals");
  4883. }
  4884. if (containsGregorMD && containsOrdinal) {
  4885. throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day");
  4886. }
  4887. const useWeekData = definiteWeekDef || normalized.weekday && !containsGregor; // configure ourselves to deal with gregorian dates or week stuff
  4888. let units,
  4889. defaultValues,
  4890. objNow = tsToObj(tsNow, offsetProvis);
  4891. if (useWeekData) {
  4892. units = orderedWeekUnits;
  4893. defaultValues = defaultWeekUnitValues;
  4894. objNow = gregorianToWeek(objNow);
  4895. } else if (containsOrdinal) {
  4896. units = orderedOrdinalUnits;
  4897. defaultValues = defaultOrdinalUnitValues;
  4898. objNow = gregorianToOrdinal(objNow);
  4899. } else {
  4900. units = orderedUnits;
  4901. defaultValues = defaultUnitValues;
  4902. } // set default values for missing stuff
  4903. let foundFirst = false;
  4904. for (const u of units) {
  4905. const v = normalized[u];
  4906. if (!isUndefined(v)) {
  4907. foundFirst = true;
  4908. } else if (foundFirst) {
  4909. normalized[u] = defaultValues[u];
  4910. } else {
  4911. normalized[u] = objNow[u];
  4912. }
  4913. } // make sure the values we have are in range
  4914. const higherOrderInvalid = useWeekData ? hasInvalidWeekData(normalized) : containsOrdinal ? hasInvalidOrdinalData(normalized) : hasInvalidGregorianData(normalized),
  4915. invalid = higherOrderInvalid || hasInvalidTimeData(normalized);
  4916. if (invalid) {
  4917. return DateTime.invalid(invalid);
  4918. } // compute the actual time
  4919. const gregorian = useWeekData ? weekToGregorian(normalized) : containsOrdinal ? ordinalToGregorian(normalized) : normalized,
  4920. [tsFinal, offsetFinal] = objToTS(gregorian, offsetProvis, zoneToUse),
  4921. inst = new DateTime({
  4922. ts: tsFinal,
  4923. zone: zoneToUse,
  4924. o: offsetFinal,
  4925. loc
  4926. }); // gregorian data + weekday serves only to validate
  4927. if (normalized.weekday && containsGregor && obj.weekday !== inst.weekday) {
  4928. return DateTime.invalid("mismatched weekday", `you can't specify both a weekday of ${normalized.weekday} and a date of ${inst.toISO()}`);
  4929. }
  4930. return inst;
  4931. }
  4932. /**
  4933. * Create a DateTime from an ISO 8601 string
  4934. * @param {string} text - the ISO string
  4935. * @param {Object} opts - options to affect the creation
  4936. * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the time to this zone
  4937. * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one
  4938. * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance
  4939. * @param {string} [opts.outputCalendar] - the output calendar to set on the resulting DateTime instance
  4940. * @param {string} [opts.numberingSystem] - the numbering system to set on the resulting DateTime instance
  4941. * @example DateTime.fromISO('2016-05-25T09:08:34.123')
  4942. * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00')
  4943. * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00', {setZone: true})
  4944. * @example DateTime.fromISO('2016-05-25T09:08:34.123', {zone: 'utc'})
  4945. * @example DateTime.fromISO('2016-W05-4')
  4946. * @return {DateTime}
  4947. */
  4948. static fromISO(text, opts = {}) {
  4949. const [vals, parsedZone] = parseISODate(text);
  4950. return parseDataToDateTime(vals, parsedZone, opts, "ISO 8601", text);
  4951. }
  4952. /**
  4953. * Create a DateTime from an RFC 2822 string
  4954. * @param {string} text - the RFC 2822 string
  4955. * @param {Object} opts - options to affect the creation
  4956. * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since the offset is always specified in the string itself, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in.
  4957. * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one
  4958. * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance
  4959. * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
  4960. * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance
  4961. * @example DateTime.fromRFC2822('25 Nov 2016 13:23:12 GMT')
  4962. * @example DateTime.fromRFC2822('Fri, 25 Nov 2016 13:23:12 +0600')
  4963. * @example DateTime.fromRFC2822('25 Nov 2016 13:23 Z')
  4964. * @return {DateTime}
  4965. */
  4966. static fromRFC2822(text, opts = {}) {
  4967. const [vals, parsedZone] = parseRFC2822Date(text);
  4968. return parseDataToDateTime(vals, parsedZone, opts, "RFC 2822", text);
  4969. }
  4970. /**
  4971. * Create a DateTime from an HTTP header date
  4972. * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1
  4973. * @param {string} text - the HTTP header date
  4974. * @param {Object} opts - options to affect the creation
  4975. * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since HTTP dates are always in UTC, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in.
  4976. * @param {boolean} [opts.setZone=false] - override the zone with the fixed-offset zone specified in the string. For HTTP dates, this is always UTC, so this option is equivalent to setting the `zone` option to 'utc', but this option is included for consistency with similar methods.
  4977. * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance
  4978. * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
  4979. * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance
  4980. * @example DateTime.fromHTTP('Sun, 06 Nov 1994 08:49:37 GMT')
  4981. * @example DateTime.fromHTTP('Sunday, 06-Nov-94 08:49:37 GMT')
  4982. * @example DateTime.fromHTTP('Sun Nov 6 08:49:37 1994')
  4983. * @return {DateTime}
  4984. */
  4985. static fromHTTP(text, opts = {}) {
  4986. const [vals, parsedZone] = parseHTTPDate(text);
  4987. return parseDataToDateTime(vals, parsedZone, opts, "HTTP", opts);
  4988. }
  4989. /**
  4990. * Create a DateTime from an input string and format string.
  4991. * Defaults to en-US if no locale has been specified, regardless of the system's locale. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/#/parsing?id=table-of-tokens).
  4992. * @param {string} text - the string to parse
  4993. * @param {string} fmt - the format the string is expected to be in (see the link below for the formats)
  4994. * @param {Object} opts - options to affect the creation
  4995. * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone
  4996. * @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one
  4997. * @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale
  4998. * @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system
  4999. * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
  5000. * @return {DateTime}
  5001. */
  5002. static fromFormat(text, fmt, opts = {}) {
  5003. if (isUndefined(text) || isUndefined(fmt)) {
  5004. throw new InvalidArgumentError("fromFormat requires an input string and a format");
  5005. }
  5006. const {
  5007. locale = null,
  5008. numberingSystem = null
  5009. } = opts,
  5010. localeToUse = Locale.fromOpts({
  5011. locale,
  5012. numberingSystem,
  5013. defaultToEN: true
  5014. }),
  5015. [vals, parsedZone, specificOffset, invalid] = parseFromTokens(localeToUse, text, fmt);
  5016. if (invalid) {
  5017. return DateTime.invalid(invalid);
  5018. } else {
  5019. return parseDataToDateTime(vals, parsedZone, opts, `format ${fmt}`, text, specificOffset);
  5020. }
  5021. }
  5022. /**
  5023. * @deprecated use fromFormat instead
  5024. */
  5025. static fromString(text, fmt, opts = {}) {
  5026. return DateTime.fromFormat(text, fmt, opts);
  5027. }
  5028. /**
  5029. * Create a DateTime from a SQL date, time, or datetime
  5030. * Defaults to en-US if no locale has been specified, regardless of the system's locale
  5031. * @param {string} text - the string to parse
  5032. * @param {Object} opts - options to affect the creation
  5033. * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone
  5034. * @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one
  5035. * @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale
  5036. * @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system
  5037. * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
  5038. * @example DateTime.fromSQL('2017-05-15')
  5039. * @example DateTime.fromSQL('2017-05-15 09:12:34')
  5040. * @example DateTime.fromSQL('2017-05-15 09:12:34.342')
  5041. * @example DateTime.fromSQL('2017-05-15 09:12:34.342+06:00')
  5042. * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles')
  5043. * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles', { setZone: true })
  5044. * @example DateTime.fromSQL('2017-05-15 09:12:34.342', { zone: 'America/Los_Angeles' })
  5045. * @example DateTime.fromSQL('09:12:34.342')
  5046. * @return {DateTime}
  5047. */
  5048. static fromSQL(text, opts = {}) {
  5049. const [vals, parsedZone] = parseSQL(text);
  5050. return parseDataToDateTime(vals, parsedZone, opts, "SQL", text);
  5051. }
  5052. /**
  5053. * Create an invalid DateTime.
  5054. * @param {DateTime} reason - simple string of why this DateTime is invalid. Should not contain parameters or anything else data-dependent
  5055. * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information
  5056. * @return {DateTime}
  5057. */
  5058. static invalid(reason, explanation = null) {
  5059. if (!reason) {
  5060. throw new InvalidArgumentError("need to specify a reason the DateTime is invalid");
  5061. }
  5062. const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
  5063. if (Settings.throwOnInvalid) {
  5064. throw new InvalidDateTimeError(invalid);
  5065. } else {
  5066. return new DateTime({
  5067. invalid
  5068. });
  5069. }
  5070. }
  5071. /**
  5072. * Check if an object is an instance of DateTime. Works across context boundaries
  5073. * @param {object} o
  5074. * @return {boolean}
  5075. */
  5076. static isDateTime(o) {
  5077. return o && o.isLuxonDateTime || false;
  5078. }
  5079. /**
  5080. * Produce the format string for a set of options
  5081. * @param formatOpts
  5082. * @param localeOpts
  5083. * @returns {string}
  5084. */
  5085. static parseFormatForOpts(formatOpts, localeOpts = {}) {
  5086. const tokenList = formatOptsToTokens(formatOpts, Locale.fromObject(localeOpts));
  5087. return !tokenList ? null : tokenList.map(t => t ? t.val : null).join("");
  5088. }
  5089. /**
  5090. * Produce the the fully expanded format token for the locale
  5091. * Does NOT quote characters, so quoted tokens will not round trip correctly
  5092. * @param fmt
  5093. * @param localeOpts
  5094. * @returns {string}
  5095. */
  5096. static expandFormat(fmt, localeOpts = {}) {
  5097. const expanded = expandMacroTokens(Formatter.parseFormat(fmt), Locale.fromObject(localeOpts));
  5098. return expanded.map(t => t.val).join("");
  5099. } // INFO
  5100. /**
  5101. * Get the value of unit.
  5102. * @param {string} unit - a unit such as 'minute' or 'day'
  5103. * @example DateTime.local(2017, 7, 4).get('month'); //=> 7
  5104. * @example DateTime.local(2017, 7, 4).get('day'); //=> 4
  5105. * @return {number}
  5106. */
  5107. get(unit) {
  5108. return this[unit];
  5109. }
  5110. /**
  5111. * Returns whether the DateTime is valid. Invalid DateTimes occur when:
  5112. * * The DateTime was created from invalid calendar information, such as the 13th month or February 30
  5113. * * The DateTime was created by an operation on another invalid date
  5114. * @type {boolean}
  5115. */
  5116. get isValid() {
  5117. return this.invalid === null;
  5118. }
  5119. /**
  5120. * Returns an error code if this DateTime is invalid, or null if the DateTime is valid
  5121. * @type {string}
  5122. */
  5123. get invalidReason() {
  5124. return this.invalid ? this.invalid.reason : null;
  5125. }
  5126. /**
  5127. * Returns an explanation of why this DateTime became invalid, or null if the DateTime is valid
  5128. * @type {string}
  5129. */
  5130. get invalidExplanation() {
  5131. return this.invalid ? this.invalid.explanation : null;
  5132. }
  5133. /**
  5134. * Get the locale of a DateTime, such 'en-GB'. The locale is used when formatting the DateTime
  5135. *
  5136. * @type {string}
  5137. */
  5138. get locale() {
  5139. return this.isValid ? this.loc.locale : null;
  5140. }
  5141. /**
  5142. * Get the numbering system of a DateTime, such 'beng'. The numbering system is used when formatting the DateTime
  5143. *
  5144. * @type {string}
  5145. */
  5146. get numberingSystem() {
  5147. return this.isValid ? this.loc.numberingSystem : null;
  5148. }
  5149. /**
  5150. * Get the output calendar of a DateTime, such 'islamic'. The output calendar is used when formatting the DateTime
  5151. *
  5152. * @type {string}
  5153. */
  5154. get outputCalendar() {
  5155. return this.isValid ? this.loc.outputCalendar : null;
  5156. }
  5157. /**
  5158. * Get the time zone associated with this DateTime.
  5159. * @type {Zone}
  5160. */
  5161. get zone() {
  5162. return this._zone;
  5163. }
  5164. /**
  5165. * Get the name of the time zone.
  5166. * @type {string}
  5167. */
  5168. get zoneName() {
  5169. return this.isValid ? this.zone.name : null;
  5170. }
  5171. /**
  5172. * Get the year
  5173. * @example DateTime.local(2017, 5, 25).year //=> 2017
  5174. * @type {number}
  5175. */
  5176. get year() {
  5177. return this.isValid ? this.c.year : NaN;
  5178. }
  5179. /**
  5180. * Get the quarter
  5181. * @example DateTime.local(2017, 5, 25).quarter //=> 2
  5182. * @type {number}
  5183. */
  5184. get quarter() {
  5185. return this.isValid ? Math.ceil(this.c.month / 3) : NaN;
  5186. }
  5187. /**
  5188. * Get the month (1-12).
  5189. * @example DateTime.local(2017, 5, 25).month //=> 5
  5190. * @type {number}
  5191. */
  5192. get month() {
  5193. return this.isValid ? this.c.month : NaN;
  5194. }
  5195. /**
  5196. * Get the day of the month (1-30ish).
  5197. * @example DateTime.local(2017, 5, 25).day //=> 25
  5198. * @type {number}
  5199. */
  5200. get day() {
  5201. return this.isValid ? this.c.day : NaN;
  5202. }
  5203. /**
  5204. * Get the hour of the day (0-23).
  5205. * @example DateTime.local(2017, 5, 25, 9).hour //=> 9
  5206. * @type {number}
  5207. */
  5208. get hour() {
  5209. return this.isValid ? this.c.hour : NaN;
  5210. }
  5211. /**
  5212. * Get the minute of the hour (0-59).
  5213. * @example DateTime.local(2017, 5, 25, 9, 30).minute //=> 30
  5214. * @type {number}
  5215. */
  5216. get minute() {
  5217. return this.isValid ? this.c.minute : NaN;
  5218. }
  5219. /**
  5220. * Get the second of the minute (0-59).
  5221. * @example DateTime.local(2017, 5, 25, 9, 30, 52).second //=> 52
  5222. * @type {number}
  5223. */
  5224. get second() {
  5225. return this.isValid ? this.c.second : NaN;
  5226. }
  5227. /**
  5228. * Get the millisecond of the second (0-999).
  5229. * @example DateTime.local(2017, 5, 25, 9, 30, 52, 654).millisecond //=> 654
  5230. * @type {number}
  5231. */
  5232. get millisecond() {
  5233. return this.isValid ? this.c.millisecond : NaN;
  5234. }
  5235. /**
  5236. * Get the week year
  5237. * @see https://en.wikipedia.org/wiki/ISO_week_date
  5238. * @example DateTime.local(2014, 12, 31).weekYear //=> 2015
  5239. * @type {number}
  5240. */
  5241. get weekYear() {
  5242. return this.isValid ? possiblyCachedWeekData(this).weekYear : NaN;
  5243. }
  5244. /**
  5245. * Get the week number of the week year (1-52ish).
  5246. * @see https://en.wikipedia.org/wiki/ISO_week_date
  5247. * @example DateTime.local(2017, 5, 25).weekNumber //=> 21
  5248. * @type {number}
  5249. */
  5250. get weekNumber() {
  5251. return this.isValid ? possiblyCachedWeekData(this).weekNumber : NaN;
  5252. }
  5253. /**
  5254. * Get the day of the week.
  5255. * 1 is Monday and 7 is Sunday
  5256. * @see https://en.wikipedia.org/wiki/ISO_week_date
  5257. * @example DateTime.local(2014, 11, 31).weekday //=> 4
  5258. * @type {number}
  5259. */
  5260. get weekday() {
  5261. return this.isValid ? possiblyCachedWeekData(this).weekday : NaN;
  5262. }
  5263. /**
  5264. * Get the ordinal (meaning the day of the year)
  5265. * @example DateTime.local(2017, 5, 25).ordinal //=> 145
  5266. * @type {number|DateTime}
  5267. */
  5268. get ordinal() {
  5269. return this.isValid ? gregorianToOrdinal(this.c).ordinal : NaN;
  5270. }
  5271. /**
  5272. * Get the human readable short month name, such as 'Oct'.
  5273. * Defaults to the system's locale if no locale has been specified
  5274. * @example DateTime.local(2017, 10, 30).monthShort //=> Oct
  5275. * @type {string}
  5276. */
  5277. get monthShort() {
  5278. return this.isValid ? Info.months("short", {
  5279. locObj: this.loc
  5280. })[this.month - 1] : null;
  5281. }
  5282. /**
  5283. * Get the human readable long month name, such as 'October'.
  5284. * Defaults to the system's locale if no locale has been specified
  5285. * @example DateTime.local(2017, 10, 30).monthLong //=> October
  5286. * @type {string}
  5287. */
  5288. get monthLong() {
  5289. return this.isValid ? Info.months("long", {
  5290. locObj: this.loc
  5291. })[this.month - 1] : null;
  5292. }
  5293. /**
  5294. * Get the human readable short weekday, such as 'Mon'.
  5295. * Defaults to the system's locale if no locale has been specified
  5296. * @example DateTime.local(2017, 10, 30).weekdayShort //=> Mon
  5297. * @type {string}
  5298. */
  5299. get weekdayShort() {
  5300. return this.isValid ? Info.weekdays("short", {
  5301. locObj: this.loc
  5302. })[this.weekday - 1] : null;
  5303. }
  5304. /**
  5305. * Get the human readable long weekday, such as 'Monday'.
  5306. * Defaults to the system's locale if no locale has been specified
  5307. * @example DateTime.local(2017, 10, 30).weekdayLong //=> Monday
  5308. * @type {string}
  5309. */
  5310. get weekdayLong() {
  5311. return this.isValid ? Info.weekdays("long", {
  5312. locObj: this.loc
  5313. })[this.weekday - 1] : null;
  5314. }
  5315. /**
  5316. * Get the UTC offset of this DateTime in minutes
  5317. * @example DateTime.now().offset //=> -240
  5318. * @example DateTime.utc().offset //=> 0
  5319. * @type {number}
  5320. */
  5321. get offset() {
  5322. return this.isValid ? +this.o : NaN;
  5323. }
  5324. /**
  5325. * Get the short human name for the zone's current offset, for example "EST" or "EDT".
  5326. * Defaults to the system's locale if no locale has been specified
  5327. * @type {string}
  5328. */
  5329. get offsetNameShort() {
  5330. if (this.isValid) {
  5331. return this.zone.offsetName(this.ts, {
  5332. format: "short",
  5333. locale: this.locale
  5334. });
  5335. } else {
  5336. return null;
  5337. }
  5338. }
  5339. /**
  5340. * Get the long human name for the zone's current offset, for example "Eastern Standard Time" or "Eastern Daylight Time".
  5341. * Defaults to the system's locale if no locale has been specified
  5342. * @type {string}
  5343. */
  5344. get offsetNameLong() {
  5345. if (this.isValid) {
  5346. return this.zone.offsetName(this.ts, {
  5347. format: "long",
  5348. locale: this.locale
  5349. });
  5350. } else {
  5351. return null;
  5352. }
  5353. }
  5354. /**
  5355. * Get whether this zone's offset ever changes, as in a DST.
  5356. * @type {boolean}
  5357. */
  5358. get isOffsetFixed() {
  5359. return this.isValid ? this.zone.isUniversal : null;
  5360. }
  5361. /**
  5362. * Get whether the DateTime is in a DST.
  5363. * @type {boolean}
  5364. */
  5365. get isInDST() {
  5366. if (this.isOffsetFixed) {
  5367. return false;
  5368. } else {
  5369. return this.offset > this.set({
  5370. month: 1,
  5371. day: 1
  5372. }).offset || this.offset > this.set({
  5373. month: 5
  5374. }).offset;
  5375. }
  5376. }
  5377. /**
  5378. * Returns true if this DateTime is in a leap year, false otherwise
  5379. * @example DateTime.local(2016).isInLeapYear //=> true
  5380. * @example DateTime.local(2013).isInLeapYear //=> false
  5381. * @type {boolean}
  5382. */
  5383. get isInLeapYear() {
  5384. return isLeapYear(this.year);
  5385. }
  5386. /**
  5387. * Returns the number of days in this DateTime's month
  5388. * @example DateTime.local(2016, 2).daysInMonth //=> 29
  5389. * @example DateTime.local(2016, 3).daysInMonth //=> 31
  5390. * @type {number}
  5391. */
  5392. get daysInMonth() {
  5393. return daysInMonth(this.year, this.month);
  5394. }
  5395. /**
  5396. * Returns the number of days in this DateTime's year
  5397. * @example DateTime.local(2016).daysInYear //=> 366
  5398. * @example DateTime.local(2013).daysInYear //=> 365
  5399. * @type {number}
  5400. */
  5401. get daysInYear() {
  5402. return this.isValid ? daysInYear(this.year) : NaN;
  5403. }
  5404. /**
  5405. * Returns the number of weeks in this DateTime's year
  5406. * @see https://en.wikipedia.org/wiki/ISO_week_date
  5407. * @example DateTime.local(2004).weeksInWeekYear //=> 53
  5408. * @example DateTime.local(2013).weeksInWeekYear //=> 52
  5409. * @type {number}
  5410. */
  5411. get weeksInWeekYear() {
  5412. return this.isValid ? weeksInWeekYear(this.weekYear) : NaN;
  5413. }
  5414. /**
  5415. * Returns the resolved Intl options for this DateTime.
  5416. * This is useful in understanding the behavior of formatting methods
  5417. * @param {Object} opts - the same options as toLocaleString
  5418. * @return {Object}
  5419. */
  5420. resolvedLocaleOptions(opts = {}) {
  5421. const {
  5422. locale,
  5423. numberingSystem,
  5424. calendar
  5425. } = Formatter.create(this.loc.clone(opts), opts).resolvedOptions(this);
  5426. return {
  5427. locale,
  5428. numberingSystem,
  5429. outputCalendar: calendar
  5430. };
  5431. } // TRANSFORM
  5432. /**
  5433. * "Set" the DateTime's zone to UTC. Returns a newly-constructed DateTime.
  5434. *
  5435. * Equivalent to {@link DateTime#setZone}('utc')
  5436. * @param {number} [offset=0] - optionally, an offset from UTC in minutes
  5437. * @param {Object} [opts={}] - options to pass to `setZone()`
  5438. * @return {DateTime}
  5439. */
  5440. toUTC(offset = 0, opts = {}) {
  5441. return this.setZone(FixedOffsetZone.instance(offset), opts);
  5442. }
  5443. /**
  5444. * "Set" the DateTime's zone to the host's local zone. Returns a newly-constructed DateTime.
  5445. *
  5446. * Equivalent to `setZone('local')`
  5447. * @return {DateTime}
  5448. */
  5449. toLocal() {
  5450. return this.setZone(Settings.defaultZone);
  5451. }
  5452. /**
  5453. * "Set" the DateTime's zone to specified zone. Returns a newly-constructed DateTime.
  5454. *
  5455. * By default, the setter keeps the underlying time the same (as in, the same timestamp), but the new instance will report different local times and consider DSTs when making computations, as with {@link DateTime#plus}. You may wish to use {@link DateTime#toLocal} and {@link DateTime#toUTC} which provide simple convenience wrappers for commonly used zones.
  5456. * @param {string|Zone} [zone='local'] - a zone identifier. As a string, that can be any IANA zone supported by the host environment, or a fixed-offset name of the form 'UTC+3', or the strings 'local' or 'utc'. You may also supply an instance of a {@link DateTime#Zone} class.
  5457. * @param {Object} opts - options
  5458. * @param {boolean} [opts.keepLocalTime=false] - If true, adjust the underlying time so that the local time stays the same, but in the target zone. You should rarely need this.
  5459. * @return {DateTime}
  5460. */
  5461. setZone(zone, {
  5462. keepLocalTime = false,
  5463. keepCalendarTime = false
  5464. } = {}) {
  5465. zone = normalizeZone(zone, Settings.defaultZone);
  5466. if (zone.equals(this.zone)) {
  5467. return this;
  5468. } else if (!zone.isValid) {
  5469. return DateTime.invalid(unsupportedZone(zone));
  5470. } else {
  5471. let newTS = this.ts;
  5472. if (keepLocalTime || keepCalendarTime) {
  5473. const offsetGuess = zone.offset(this.ts);
  5474. const asObj = this.toObject();
  5475. [newTS] = objToTS(asObj, offsetGuess, zone);
  5476. }
  5477. return clone(this, {
  5478. ts: newTS,
  5479. zone
  5480. });
  5481. }
  5482. }
  5483. /**
  5484. * "Set" the locale, numberingSystem, or outputCalendar. Returns a newly-constructed DateTime.
  5485. * @param {Object} properties - the properties to set
  5486. * @example DateTime.local(2017, 5, 25).reconfigure({ locale: 'en-GB' })
  5487. * @return {DateTime}
  5488. */
  5489. reconfigure({
  5490. locale,
  5491. numberingSystem,
  5492. outputCalendar
  5493. } = {}) {
  5494. const loc = this.loc.clone({
  5495. locale,
  5496. numberingSystem,
  5497. outputCalendar
  5498. });
  5499. return clone(this, {
  5500. loc
  5501. });
  5502. }
  5503. /**
  5504. * "Set" the locale. Returns a newly-constructed DateTime.
  5505. * Just a convenient alias for reconfigure({ locale })
  5506. * @example DateTime.local(2017, 5, 25).setLocale('en-GB')
  5507. * @return {DateTime}
  5508. */
  5509. setLocale(locale) {
  5510. return this.reconfigure({
  5511. locale
  5512. });
  5513. }
  5514. /**
  5515. * "Set" the values of specified units. Returns a newly-constructed DateTime.
  5516. * You can only set units with this method; for "setting" metadata, see {@link DateTime#reconfigure} and {@link DateTime#setZone}.
  5517. * @param {Object} values - a mapping of units to numbers
  5518. * @example dt.set({ year: 2017 })
  5519. * @example dt.set({ hour: 8, minute: 30 })
  5520. * @example dt.set({ weekday: 5 })
  5521. * @example dt.set({ year: 2005, ordinal: 234 })
  5522. * @return {DateTime}
  5523. */
  5524. set(values) {
  5525. if (!this.isValid) return this;
  5526. const normalized = normalizeObject(values, normalizeUnit),
  5527. settingWeekStuff = !isUndefined(normalized.weekYear) || !isUndefined(normalized.weekNumber) || !isUndefined(normalized.weekday),
  5528. containsOrdinal = !isUndefined(normalized.ordinal),
  5529. containsGregorYear = !isUndefined(normalized.year),
  5530. containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day),
  5531. containsGregor = containsGregorYear || containsGregorMD,
  5532. definiteWeekDef = normalized.weekYear || normalized.weekNumber;
  5533. if ((containsGregor || containsOrdinal) && definiteWeekDef) {
  5534. throw new ConflictingSpecificationError("Can't mix weekYear/weekNumber units with year/month/day or ordinals");
  5535. }
  5536. if (containsGregorMD && containsOrdinal) {
  5537. throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day");
  5538. }
  5539. let mixed;
  5540. if (settingWeekStuff) {
  5541. mixed = weekToGregorian({ ...gregorianToWeek(this.c),
  5542. ...normalized
  5543. });
  5544. } else if (!isUndefined(normalized.ordinal)) {
  5545. mixed = ordinalToGregorian({ ...gregorianToOrdinal(this.c),
  5546. ...normalized
  5547. });
  5548. } else {
  5549. mixed = { ...this.toObject(),
  5550. ...normalized
  5551. }; // if we didn't set the day but we ended up on an overflow date,
  5552. // use the last day of the right month
  5553. if (isUndefined(normalized.day)) {
  5554. mixed.day = Math.min(daysInMonth(mixed.year, mixed.month), mixed.day);
  5555. }
  5556. }
  5557. const [ts, o] = objToTS(mixed, this.o, this.zone);
  5558. return clone(this, {
  5559. ts,
  5560. o
  5561. });
  5562. }
  5563. /**
  5564. * Add a period of time to this DateTime and return the resulting DateTime
  5565. *
  5566. * Adding hours, minutes, seconds, or milliseconds increases the timestamp by the right number of milliseconds. Adding days, months, or years shifts the calendar, accounting for DSTs and leap years along the way. Thus, `dt.plus({ hours: 24 })` may result in a different time than `dt.plus({ days: 1 })` if there's a DST shift in between.
  5567. * @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()
  5568. * @example DateTime.now().plus(123) //~> in 123 milliseconds
  5569. * @example DateTime.now().plus({ minutes: 15 }) //~> in 15 minutes
  5570. * @example DateTime.now().plus({ days: 1 }) //~> this time tomorrow
  5571. * @example DateTime.now().plus({ days: -1 }) //~> this time yesterday
  5572. * @example DateTime.now().plus({ hours: 3, minutes: 13 }) //~> in 3 hr, 13 min
  5573. * @example DateTime.now().plus(Duration.fromObject({ hours: 3, minutes: 13 })) //~> in 3 hr, 13 min
  5574. * @return {DateTime}
  5575. */
  5576. plus(duration) {
  5577. if (!this.isValid) return this;
  5578. const dur = Duration.fromDurationLike(duration);
  5579. return clone(this, adjustTime(this, dur));
  5580. }
  5581. /**
  5582. * Subtract a period of time to this DateTime and return the resulting DateTime
  5583. * See {@link DateTime#plus}
  5584. * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()
  5585. @return {DateTime}
  5586. */
  5587. minus(duration) {
  5588. if (!this.isValid) return this;
  5589. const dur = Duration.fromDurationLike(duration).negate();
  5590. return clone(this, adjustTime(this, dur));
  5591. }
  5592. /**
  5593. * "Set" this DateTime to the beginning of a unit of time.
  5594. * @param {string} unit - The unit to go to the beginning of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'.
  5595. * @example DateTime.local(2014, 3, 3).startOf('month').toISODate(); //=> '2014-03-01'
  5596. * @example DateTime.local(2014, 3, 3).startOf('year').toISODate(); //=> '2014-01-01'
  5597. * @example DateTime.local(2014, 3, 3).startOf('week').toISODate(); //=> '2014-03-03', weeks always start on Mondays
  5598. * @example DateTime.local(2014, 3, 3, 5, 30).startOf('day').toISOTime(); //=> '00:00.000-05:00'
  5599. * @example DateTime.local(2014, 3, 3, 5, 30).startOf('hour').toISOTime(); //=> '05:00:00.000-05:00'
  5600. * @return {DateTime}
  5601. */
  5602. startOf(unit) {
  5603. if (!this.isValid) return this;
  5604. const o = {},
  5605. normalizedUnit = Duration.normalizeUnit(unit);
  5606. switch (normalizedUnit) {
  5607. case "years":
  5608. o.month = 1;
  5609. // falls through
  5610. case "quarters":
  5611. case "months":
  5612. o.day = 1;
  5613. // falls through
  5614. case "weeks":
  5615. case "days":
  5616. o.hour = 0;
  5617. // falls through
  5618. case "hours":
  5619. o.minute = 0;
  5620. // falls through
  5621. case "minutes":
  5622. o.second = 0;
  5623. // falls through
  5624. case "seconds":
  5625. o.millisecond = 0;
  5626. break;
  5627. // no default, invalid units throw in normalizeUnit()
  5628. }
  5629. if (normalizedUnit === "weeks") {
  5630. o.weekday = 1;
  5631. }
  5632. if (normalizedUnit === "quarters") {
  5633. const q = Math.ceil(this.month / 3);
  5634. o.month = (q - 1) * 3 + 1;
  5635. }
  5636. return this.set(o);
  5637. }
  5638. /**
  5639. * "Set" this DateTime to the end (meaning the last millisecond) of a unit of time
  5640. * @param {string} unit - The unit to go to the end of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'.
  5641. * @example DateTime.local(2014, 3, 3).endOf('month').toISO(); //=> '2014-03-31T23:59:59.999-05:00'
  5642. * @example DateTime.local(2014, 3, 3).endOf('year').toISO(); //=> '2014-12-31T23:59:59.999-05:00'
  5643. * @example DateTime.local(2014, 3, 3).endOf('week').toISO(); // => '2014-03-09T23:59:59.999-05:00', weeks start on Mondays
  5644. * @example DateTime.local(2014, 3, 3, 5, 30).endOf('day').toISO(); //=> '2014-03-03T23:59:59.999-05:00'
  5645. * @example DateTime.local(2014, 3, 3, 5, 30).endOf('hour').toISO(); //=> '2014-03-03T05:59:59.999-05:00'
  5646. * @return {DateTime}
  5647. */
  5648. endOf(unit) {
  5649. return this.isValid ? this.plus({
  5650. [unit]: 1
  5651. }).startOf(unit).minus(1) : this;
  5652. } // OUTPUT
  5653. /**
  5654. * Returns a string representation of this DateTime formatted according to the specified format string.
  5655. * **You may not want this.** See {@link DateTime#toLocaleString} for a more flexible formatting tool. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/#/formatting?id=table-of-tokens).
  5656. * Defaults to en-US if no locale has been specified, regardless of the system's locale.
  5657. * @param {string} fmt - the format string
  5658. * @param {Object} opts - opts to override the configuration options on this DateTime
  5659. * @example DateTime.now().toFormat('yyyy LLL dd') //=> '2017 Apr 22'
  5660. * @example DateTime.now().setLocale('fr').toFormat('yyyy LLL dd') //=> '2017 avr. 22'
  5661. * @example DateTime.now().toFormat('yyyy LLL dd', { locale: "fr" }) //=> '2017 avr. 22'
  5662. * @example DateTime.now().toFormat("HH 'hours and' mm 'minutes'") //=> '20 hours and 55 minutes'
  5663. * @return {string}
  5664. */
  5665. toFormat(fmt, opts = {}) {
  5666. return this.isValid ? Formatter.create(this.loc.redefaultToEN(opts)).formatDateTimeFromString(this, fmt) : INVALID;
  5667. }
  5668. /**
  5669. * Returns a localized string representing this date. Accepts the same options as the Intl.DateTimeFormat constructor and any presets defined by Luxon, such as `DateTime.DATE_FULL` or `DateTime.TIME_SIMPLE`.
  5670. * The exact behavior of this method is browser-specific, but in general it will return an appropriate representation
  5671. * of the DateTime in the assigned locale.
  5672. * Defaults to the system's locale if no locale has been specified
  5673. * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
  5674. * @param formatOpts {Object} - Intl.DateTimeFormat constructor options and configuration options
  5675. * @param {Object} opts - opts to override the configuration options on this DateTime
  5676. * @example DateTime.now().toLocaleString(); //=> 4/20/2017
  5677. * @example DateTime.now().setLocale('en-gb').toLocaleString(); //=> '20/04/2017'
  5678. * @example DateTime.now().toLocaleString(DateTime.DATE_FULL); //=> 'April 20, 2017'
  5679. * @example DateTime.now().toLocaleString(DateTime.DATE_FULL, { locale: 'fr' }); //=> '28 août 2022'
  5680. * @example DateTime.now().toLocaleString(DateTime.TIME_SIMPLE); //=> '11:32 AM'
  5681. * @example DateTime.now().toLocaleString(DateTime.DATETIME_SHORT); //=> '4/20/2017, 11:32 AM'
  5682. * @example DateTime.now().toLocaleString({ weekday: 'long', month: 'long', day: '2-digit' }); //=> 'Thursday, April 20'
  5683. * @example DateTime.now().toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }); //=> 'Thu, Apr 20, 11:27 AM'
  5684. * @example DateTime.now().toLocaleString({ hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }); //=> '11:32'
  5685. * @return {string}
  5686. */
  5687. toLocaleString(formatOpts = DATE_SHORT, opts = {}) {
  5688. return this.isValid ? Formatter.create(this.loc.clone(opts), formatOpts).formatDateTime(this) : INVALID;
  5689. }
  5690. /**
  5691. * Returns an array of format "parts", meaning individual tokens along with metadata. This is allows callers to post-process individual sections of the formatted output.
  5692. * Defaults to the system's locale if no locale has been specified
  5693. * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/formatToParts
  5694. * @param opts {Object} - Intl.DateTimeFormat constructor options, same as `toLocaleString`.
  5695. * @example DateTime.now().toLocaleParts(); //=> [
  5696. * //=> { type: 'day', value: '25' },
  5697. * //=> { type: 'literal', value: '/' },
  5698. * //=> { type: 'month', value: '05' },
  5699. * //=> { type: 'literal', value: '/' },
  5700. * //=> { type: 'year', value: '1982' }
  5701. * //=> ]
  5702. */
  5703. toLocaleParts(opts = {}) {
  5704. return this.isValid ? Formatter.create(this.loc.clone(opts), opts).formatDateTimeParts(this) : [];
  5705. }
  5706. /**
  5707. * Returns an ISO 8601-compliant string representation of this DateTime
  5708. * @param {Object} opts - options
  5709. * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0
  5710. * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0
  5711. * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'
  5712. * @param {boolean} [opts.extendedZone=false] - add the time zone format extension
  5713. * @param {string} [opts.format='extended'] - choose between the basic and extended format
  5714. * @example DateTime.utc(1983, 5, 25).toISO() //=> '1982-05-25T00:00:00.000Z'
  5715. * @example DateTime.now().toISO() //=> '2017-04-22T20:47:05.335-04:00'
  5716. * @example DateTime.now().toISO({ includeOffset: false }) //=> '2017-04-22T20:47:05.335'
  5717. * @example DateTime.now().toISO({ format: 'basic' }) //=> '20170422T204705.335-0400'
  5718. * @return {string}
  5719. */
  5720. toISO({
  5721. format = "extended",
  5722. suppressSeconds = false,
  5723. suppressMilliseconds = false,
  5724. includeOffset = true,
  5725. extendedZone = false
  5726. } = {}) {
  5727. if (!this.isValid) {
  5728. return null;
  5729. }
  5730. const ext = format === "extended";
  5731. let c = toISODate(this, ext);
  5732. c += "T";
  5733. c += toISOTime(this, ext, suppressSeconds, suppressMilliseconds, includeOffset, extendedZone);
  5734. return c;
  5735. }
  5736. /**
  5737. * Returns an ISO 8601-compliant string representation of this DateTime's date component
  5738. * @param {Object} opts - options
  5739. * @param {string} [opts.format='extended'] - choose between the basic and extended format
  5740. * @example DateTime.utc(1982, 5, 25).toISODate() //=> '1982-05-25'
  5741. * @example DateTime.utc(1982, 5, 25).toISODate({ format: 'basic' }) //=> '19820525'
  5742. * @return {string}
  5743. */
  5744. toISODate({
  5745. format = "extended"
  5746. } = {}) {
  5747. if (!this.isValid) {
  5748. return null;
  5749. }
  5750. return toISODate(this, format === "extended");
  5751. }
  5752. /**
  5753. * Returns an ISO 8601-compliant string representation of this DateTime's week date
  5754. * @example DateTime.utc(1982, 5, 25).toISOWeekDate() //=> '1982-W21-2'
  5755. * @return {string}
  5756. */
  5757. toISOWeekDate() {
  5758. return toTechFormat(this, "kkkk-'W'WW-c");
  5759. }
  5760. /**
  5761. * Returns an ISO 8601-compliant string representation of this DateTime's time component
  5762. * @param {Object} opts - options
  5763. * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0
  5764. * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0
  5765. * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'
  5766. * @param {boolean} [opts.extendedZone=true] - add the time zone format extension
  5767. * @param {boolean} [opts.includePrefix=false] - include the `T` prefix
  5768. * @param {string} [opts.format='extended'] - choose between the basic and extended format
  5769. * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime() //=> '07:34:19.361Z'
  5770. * @example DateTime.utc().set({ hour: 7, minute: 34, seconds: 0, milliseconds: 0 }).toISOTime({ suppressSeconds: true }) //=> '07:34Z'
  5771. * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ format: 'basic' }) //=> '073419.361Z'
  5772. * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ includePrefix: true }) //=> 'T07:34:19.361Z'
  5773. * @return {string}
  5774. */
  5775. toISOTime({
  5776. suppressMilliseconds = false,
  5777. suppressSeconds = false,
  5778. includeOffset = true,
  5779. includePrefix = false,
  5780. extendedZone = false,
  5781. format = "extended"
  5782. } = {}) {
  5783. if (!this.isValid) {
  5784. return null;
  5785. }
  5786. let c = includePrefix ? "T" : "";
  5787. return c + toISOTime(this, format === "extended", suppressSeconds, suppressMilliseconds, includeOffset, extendedZone);
  5788. }
  5789. /**
  5790. * Returns an RFC 2822-compatible string representation of this DateTime
  5791. * @example DateTime.utc(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 +0000'
  5792. * @example DateTime.local(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 -0400'
  5793. * @return {string}
  5794. */
  5795. toRFC2822() {
  5796. return toTechFormat(this, "EEE, dd LLL yyyy HH:mm:ss ZZZ", false);
  5797. }
  5798. /**
  5799. * Returns a string representation of this DateTime appropriate for use in HTTP headers. The output is always expressed in GMT.
  5800. * Specifically, the string conforms to RFC 1123.
  5801. * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1
  5802. * @example DateTime.utc(2014, 7, 13).toHTTP() //=> 'Sun, 13 Jul 2014 00:00:00 GMT'
  5803. * @example DateTime.utc(2014, 7, 13, 19).toHTTP() //=> 'Sun, 13 Jul 2014 19:00:00 GMT'
  5804. * @return {string}
  5805. */
  5806. toHTTP() {
  5807. return toTechFormat(this.toUTC(), "EEE, dd LLL yyyy HH:mm:ss 'GMT'");
  5808. }
  5809. /**
  5810. * Returns a string representation of this DateTime appropriate for use in SQL Date
  5811. * @example DateTime.utc(2014, 7, 13).toSQLDate() //=> '2014-07-13'
  5812. * @return {string}
  5813. */
  5814. toSQLDate() {
  5815. if (!this.isValid) {
  5816. return null;
  5817. }
  5818. return toISODate(this, true);
  5819. }
  5820. /**
  5821. * Returns a string representation of this DateTime appropriate for use in SQL Time
  5822. * @param {Object} opts - options
  5823. * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset.
  5824. * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'
  5825. * @param {boolean} [opts.includeOffsetSpace=true] - include the space between the time and the offset, such as '05:15:16.345 -04:00'
  5826. * @example DateTime.utc().toSQL() //=> '05:15:16.345'
  5827. * @example DateTime.now().toSQL() //=> '05:15:16.345 -04:00'
  5828. * @example DateTime.now().toSQL({ includeOffset: false }) //=> '05:15:16.345'
  5829. * @example DateTime.now().toSQL({ includeZone: false }) //=> '05:15:16.345 America/New_York'
  5830. * @return {string}
  5831. */
  5832. toSQLTime({
  5833. includeOffset = true,
  5834. includeZone = false,
  5835. includeOffsetSpace = true
  5836. } = {}) {
  5837. let fmt = "HH:mm:ss.SSS";
  5838. if (includeZone || includeOffset) {
  5839. if (includeOffsetSpace) {
  5840. fmt += " ";
  5841. }
  5842. if (includeZone) {
  5843. fmt += "z";
  5844. } else if (includeOffset) {
  5845. fmt += "ZZ";
  5846. }
  5847. }
  5848. return toTechFormat(this, fmt, true);
  5849. }
  5850. /**
  5851. * Returns a string representation of this DateTime appropriate for use in SQL DateTime
  5852. * @param {Object} opts - options
  5853. * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset.
  5854. * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'
  5855. * @param {boolean} [opts.includeOffsetSpace=true] - include the space between the time and the offset, such as '05:15:16.345 -04:00'
  5856. * @example DateTime.utc(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 Z'
  5857. * @example DateTime.local(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 -04:00'
  5858. * @example DateTime.local(2014, 7, 13).toSQL({ includeOffset: false }) //=> '2014-07-13 00:00:00.000'
  5859. * @example DateTime.local(2014, 7, 13).toSQL({ includeZone: true }) //=> '2014-07-13 00:00:00.000 America/New_York'
  5860. * @return {string}
  5861. */
  5862. toSQL(opts = {}) {
  5863. if (!this.isValid) {
  5864. return null;
  5865. }
  5866. return `${this.toSQLDate()} ${this.toSQLTime(opts)}`;
  5867. }
  5868. /**
  5869. * Returns a string representation of this DateTime appropriate for debugging
  5870. * @return {string}
  5871. */
  5872. toString() {
  5873. return this.isValid ? this.toISO() : INVALID;
  5874. }
  5875. /**
  5876. * Returns the epoch milliseconds of this DateTime. Alias of {@link DateTime#toMillis}
  5877. * @return {number}
  5878. */
  5879. valueOf() {
  5880. return this.toMillis();
  5881. }
  5882. /**
  5883. * Returns the epoch milliseconds of this DateTime.
  5884. * @return {number}
  5885. */
  5886. toMillis() {
  5887. return this.isValid ? this.ts : NaN;
  5888. }
  5889. /**
  5890. * Returns the epoch seconds of this DateTime.
  5891. * @return {number}
  5892. */
  5893. toSeconds() {
  5894. return this.isValid ? this.ts / 1000 : NaN;
  5895. }
  5896. /**
  5897. * Returns the epoch seconds (as a whole number) of this DateTime.
  5898. * @return {number}
  5899. */
  5900. toUnixInteger() {
  5901. return this.isValid ? Math.floor(this.ts / 1000) : NaN;
  5902. }
  5903. /**
  5904. * Returns an ISO 8601 representation of this DateTime appropriate for use in JSON.
  5905. * @return {string}
  5906. */
  5907. toJSON() {
  5908. return this.toISO();
  5909. }
  5910. /**
  5911. * Returns a BSON serializable equivalent to this DateTime.
  5912. * @return {Date}
  5913. */
  5914. toBSON() {
  5915. return this.toJSDate();
  5916. }
  5917. /**
  5918. * Returns a JavaScript object with this DateTime's year, month, day, and so on.
  5919. * @param opts - options for generating the object
  5920. * @param {boolean} [opts.includeConfig=false] - include configuration attributes in the output
  5921. * @example DateTime.now().toObject() //=> { year: 2017, month: 4, day: 22, hour: 20, minute: 49, second: 42, millisecond: 268 }
  5922. * @return {Object}
  5923. */
  5924. toObject(opts = {}) {
  5925. if (!this.isValid) return {};
  5926. const base = { ...this.c
  5927. };
  5928. if (opts.includeConfig) {
  5929. base.outputCalendar = this.outputCalendar;
  5930. base.numberingSystem = this.loc.numberingSystem;
  5931. base.locale = this.loc.locale;
  5932. }
  5933. return base;
  5934. }
  5935. /**
  5936. * Returns a JavaScript Date equivalent to this DateTime.
  5937. * @return {Date}
  5938. */
  5939. toJSDate() {
  5940. return new Date(this.isValid ? this.ts : NaN);
  5941. } // COMPARE
  5942. /**
  5943. * Return the difference between two DateTimes as a Duration.
  5944. * @param {DateTime} otherDateTime - the DateTime to compare this one to
  5945. * @param {string|string[]} [unit=['milliseconds']] - the unit or array of units (such as 'hours' or 'days') to include in the duration.
  5946. * @param {Object} opts - options that affect the creation of the Duration
  5947. * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
  5948. * @example
  5949. * var i1 = DateTime.fromISO('1982-05-25T09:45'),
  5950. * i2 = DateTime.fromISO('1983-10-14T10:30');
  5951. * i2.diff(i1).toObject() //=> { milliseconds: 43807500000 }
  5952. * i2.diff(i1, 'hours').toObject() //=> { hours: 12168.75 }
  5953. * i2.diff(i1, ['months', 'days']).toObject() //=> { months: 16, days: 19.03125 }
  5954. * i2.diff(i1, ['months', 'days', 'hours']).toObject() //=> { months: 16, days: 19, hours: 0.75 }
  5955. * @return {Duration}
  5956. */
  5957. diff(otherDateTime, unit = "milliseconds", opts = {}) {
  5958. if (!this.isValid || !otherDateTime.isValid) {
  5959. return Duration.invalid("created by diffing an invalid DateTime");
  5960. }
  5961. const durOpts = {
  5962. locale: this.locale,
  5963. numberingSystem: this.numberingSystem,
  5964. ...opts
  5965. };
  5966. const units = maybeArray(unit).map(Duration.normalizeUnit),
  5967. otherIsLater = otherDateTime.valueOf() > this.valueOf(),
  5968. earlier = otherIsLater ? this : otherDateTime,
  5969. later = otherIsLater ? otherDateTime : this,
  5970. diffed = diff(earlier, later, units, durOpts);
  5971. return otherIsLater ? diffed.negate() : diffed;
  5972. }
  5973. /**
  5974. * Return the difference between this DateTime and right now.
  5975. * See {@link DateTime#diff}
  5976. * @param {string|string[]} [unit=['milliseconds']] - the unit or units units (such as 'hours' or 'days') to include in the duration
  5977. * @param {Object} opts - options that affect the creation of the Duration
  5978. * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
  5979. * @return {Duration}
  5980. */
  5981. diffNow(unit = "milliseconds", opts = {}) {
  5982. return this.diff(DateTime.now(), unit, opts);
  5983. }
  5984. /**
  5985. * Return an Interval spanning between this DateTime and another DateTime
  5986. * @param {DateTime} otherDateTime - the other end point of the Interval
  5987. * @return {Interval}
  5988. */
  5989. until(otherDateTime) {
  5990. return this.isValid ? Interval.fromDateTimes(this, otherDateTime) : this;
  5991. }
  5992. /**
  5993. * Return whether this DateTime is in the same unit of time as another DateTime.
  5994. * Higher-order units must also be identical for this function to return `true`.
  5995. * Note that time zones are **ignored** in this comparison, which compares the **local** calendar time. Use {@link DateTime#setZone} to convert one of the dates if needed.
  5996. * @param {DateTime} otherDateTime - the other DateTime
  5997. * @param {string} unit - the unit of time to check sameness on
  5998. * @example DateTime.now().hasSame(otherDT, 'day'); //~> true if otherDT is in the same current calendar day
  5999. * @return {boolean}
  6000. */
  6001. hasSame(otherDateTime, unit) {
  6002. if (!this.isValid) return false;
  6003. const inputMs = otherDateTime.valueOf();
  6004. const adjustedToZone = this.setZone(otherDateTime.zone, {
  6005. keepLocalTime: true
  6006. });
  6007. return adjustedToZone.startOf(unit) <= inputMs && inputMs <= adjustedToZone.endOf(unit);
  6008. }
  6009. /**
  6010. * Equality check
  6011. * Two DateTimes are equal iff they represent the same millisecond, have the same zone and location, and are both valid.
  6012. * To compare just the millisecond values, use `+dt1 === +dt2`.
  6013. * @param {DateTime} other - the other DateTime
  6014. * @return {boolean}
  6015. */
  6016. equals(other) {
  6017. return this.isValid && other.isValid && this.valueOf() === other.valueOf() && this.zone.equals(other.zone) && this.loc.equals(other.loc);
  6018. }
  6019. /**
  6020. * Returns a string representation of a this time relative to now, such as "in two days". Can only internationalize if your
  6021. * platform supports Intl.RelativeTimeFormat. Rounds down by default.
  6022. * @param {Object} options - options that affect the output
  6023. * @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now.
  6024. * @param {string} [options.style="long"] - the style of units, must be "long", "short", or "narrow"
  6025. * @param {string|string[]} options.unit - use a specific unit or array of units; if omitted, or an array, the method will pick the best unit. Use an array or one of "years", "quarters", "months", "weeks", "days", "hours", "minutes", or "seconds"
  6026. * @param {boolean} [options.round=true] - whether to round the numbers in the output.
  6027. * @param {number} [options.padding=0] - padding in milliseconds. This allows you to round up the result if it fits inside the threshold. Don't use in combination with {round: false} because the decimal output will include the padding.
  6028. * @param {string} options.locale - override the locale of this DateTime
  6029. * @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this
  6030. * @example DateTime.now().plus({ days: 1 }).toRelative() //=> "in 1 day"
  6031. * @example DateTime.now().setLocale("es").toRelative({ days: 1 }) //=> "dentro de 1 día"
  6032. * @example DateTime.now().plus({ days: 1 }).toRelative({ locale: "fr" }) //=> "dans 23 heures"
  6033. * @example DateTime.now().minus({ days: 2 }).toRelative() //=> "2 days ago"
  6034. * @example DateTime.now().minus({ days: 2 }).toRelative({ unit: "hours" }) //=> "48 hours ago"
  6035. * @example DateTime.now().minus({ hours: 36 }).toRelative({ round: false }) //=> "1.5 days ago"
  6036. */
  6037. toRelative(options = {}) {
  6038. if (!this.isValid) return null;
  6039. const base = options.base || DateTime.fromObject({}, {
  6040. zone: this.zone
  6041. }),
  6042. padding = options.padding ? this < base ? -options.padding : options.padding : 0;
  6043. let units = ["years", "months", "days", "hours", "minutes", "seconds"];
  6044. let unit = options.unit;
  6045. if (Array.isArray(options.unit)) {
  6046. units = options.unit;
  6047. unit = undefined;
  6048. }
  6049. return diffRelative(base, this.plus(padding), { ...options,
  6050. numeric: "always",
  6051. units,
  6052. unit
  6053. });
  6054. }
  6055. /**
  6056. * Returns a string representation of this date relative to today, such as "yesterday" or "next month".
  6057. * Only internationalizes on platforms that supports Intl.RelativeTimeFormat.
  6058. * @param {Object} options - options that affect the output
  6059. * @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now.
  6060. * @param {string} options.locale - override the locale of this DateTime
  6061. * @param {string} options.unit - use a specific unit; if omitted, the method will pick the unit. Use one of "years", "quarters", "months", "weeks", or "days"
  6062. * @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this
  6063. * @example DateTime.now().plus({ days: 1 }).toRelativeCalendar() //=> "tomorrow"
  6064. * @example DateTime.now().setLocale("es").plus({ days: 1 }).toRelative() //=> ""mañana"
  6065. * @example DateTime.now().plus({ days: 1 }).toRelativeCalendar({ locale: "fr" }) //=> "demain"
  6066. * @example DateTime.now().minus({ days: 2 }).toRelativeCalendar() //=> "2 days ago"
  6067. */
  6068. toRelativeCalendar(options = {}) {
  6069. if (!this.isValid) return null;
  6070. return diffRelative(options.base || DateTime.fromObject({}, {
  6071. zone: this.zone
  6072. }), this, { ...options,
  6073. numeric: "auto",
  6074. units: ["years", "months", "days"],
  6075. calendary: true
  6076. });
  6077. }
  6078. /**
  6079. * Return the min of several date times
  6080. * @param {...DateTime} dateTimes - the DateTimes from which to choose the minimum
  6081. * @return {DateTime} the min DateTime, or undefined if called with no argument
  6082. */
  6083. static min(...dateTimes) {
  6084. if (!dateTimes.every(DateTime.isDateTime)) {
  6085. throw new InvalidArgumentError("min requires all arguments be DateTimes");
  6086. }
  6087. return bestBy(dateTimes, i => i.valueOf(), Math.min);
  6088. }
  6089. /**
  6090. * Return the max of several date times
  6091. * @param {...DateTime} dateTimes - the DateTimes from which to choose the maximum
  6092. * @return {DateTime} the max DateTime, or undefined if called with no argument
  6093. */
  6094. static max(...dateTimes) {
  6095. if (!dateTimes.every(DateTime.isDateTime)) {
  6096. throw new InvalidArgumentError("max requires all arguments be DateTimes");
  6097. }
  6098. return bestBy(dateTimes, i => i.valueOf(), Math.max);
  6099. } // MISC
  6100. /**
  6101. * Explain how a string would be parsed by fromFormat()
  6102. * @param {string} text - the string to parse
  6103. * @param {string} fmt - the format the string is expected to be in (see description)
  6104. * @param {Object} options - options taken by fromFormat()
  6105. * @return {Object}
  6106. */
  6107. static fromFormatExplain(text, fmt, options = {}) {
  6108. const {
  6109. locale = null,
  6110. numberingSystem = null
  6111. } = options,
  6112. localeToUse = Locale.fromOpts({
  6113. locale,
  6114. numberingSystem,
  6115. defaultToEN: true
  6116. });
  6117. return explainFromTokens(localeToUse, text, fmt);
  6118. }
  6119. /**
  6120. * @deprecated use fromFormatExplain instead
  6121. */
  6122. static fromStringExplain(text, fmt, options = {}) {
  6123. return DateTime.fromFormatExplain(text, fmt, options);
  6124. } // FORMAT PRESETS
  6125. /**
  6126. * {@link DateTime#toLocaleString} format like 10/14/1983
  6127. * @type {Object}
  6128. */
  6129. static get DATE_SHORT() {
  6130. return DATE_SHORT;
  6131. }
  6132. /**
  6133. * {@link DateTime#toLocaleString} format like 'Oct 14, 1983'
  6134. * @type {Object}
  6135. */
  6136. static get DATE_MED() {
  6137. return DATE_MED;
  6138. }
  6139. /**
  6140. * {@link DateTime#toLocaleString} format like 'Fri, Oct 14, 1983'
  6141. * @type {Object}
  6142. */
  6143. static get DATE_MED_WITH_WEEKDAY() {
  6144. return DATE_MED_WITH_WEEKDAY;
  6145. }
  6146. /**
  6147. * {@link DateTime#toLocaleString} format like 'October 14, 1983'
  6148. * @type {Object}
  6149. */
  6150. static get DATE_FULL() {
  6151. return DATE_FULL;
  6152. }
  6153. /**
  6154. * {@link DateTime#toLocaleString} format like 'Tuesday, October 14, 1983'
  6155. * @type {Object}
  6156. */
  6157. static get DATE_HUGE() {
  6158. return DATE_HUGE;
  6159. }
  6160. /**
  6161. * {@link DateTime#toLocaleString} format like '09:30 AM'. Only 12-hour if the locale is.
  6162. * @type {Object}
  6163. */
  6164. static get TIME_SIMPLE() {
  6165. return TIME_SIMPLE;
  6166. }
  6167. /**
  6168. * {@link DateTime#toLocaleString} format like '09:30:23 AM'. Only 12-hour if the locale is.
  6169. * @type {Object}
  6170. */
  6171. static get TIME_WITH_SECONDS() {
  6172. return TIME_WITH_SECONDS;
  6173. }
  6174. /**
  6175. * {@link DateTime#toLocaleString} format like '09:30:23 AM EDT'. Only 12-hour if the locale is.
  6176. * @type {Object}
  6177. */
  6178. static get TIME_WITH_SHORT_OFFSET() {
  6179. return TIME_WITH_SHORT_OFFSET;
  6180. }
  6181. /**
  6182. * {@link DateTime#toLocaleString} format like '09:30:23 AM Eastern Daylight Time'. Only 12-hour if the locale is.
  6183. * @type {Object}
  6184. */
  6185. static get TIME_WITH_LONG_OFFSET() {
  6186. return TIME_WITH_LONG_OFFSET;
  6187. }
  6188. /**
  6189. * {@link DateTime#toLocaleString} format like '09:30', always 24-hour.
  6190. * @type {Object}
  6191. */
  6192. static get TIME_24_SIMPLE() {
  6193. return TIME_24_SIMPLE;
  6194. }
  6195. /**
  6196. * {@link DateTime#toLocaleString} format like '09:30:23', always 24-hour.
  6197. * @type {Object}
  6198. */
  6199. static get TIME_24_WITH_SECONDS() {
  6200. return TIME_24_WITH_SECONDS;
  6201. }
  6202. /**
  6203. * {@link DateTime#toLocaleString} format like '09:30:23 EDT', always 24-hour.
  6204. * @type {Object}
  6205. */
  6206. static get TIME_24_WITH_SHORT_OFFSET() {
  6207. return TIME_24_WITH_SHORT_OFFSET;
  6208. }
  6209. /**
  6210. * {@link DateTime#toLocaleString} format like '09:30:23 Eastern Daylight Time', always 24-hour.
  6211. * @type {Object}
  6212. */
  6213. static get TIME_24_WITH_LONG_OFFSET() {
  6214. return TIME_24_WITH_LONG_OFFSET;
  6215. }
  6216. /**
  6217. * {@link DateTime#toLocaleString} format like '10/14/1983, 9:30 AM'. Only 12-hour if the locale is.
  6218. * @type {Object}
  6219. */
  6220. static get DATETIME_SHORT() {
  6221. return DATETIME_SHORT;
  6222. }
  6223. /**
  6224. * {@link DateTime#toLocaleString} format like '10/14/1983, 9:30:33 AM'. Only 12-hour if the locale is.
  6225. * @type {Object}
  6226. */
  6227. static get DATETIME_SHORT_WITH_SECONDS() {
  6228. return DATETIME_SHORT_WITH_SECONDS;
  6229. }
  6230. /**
  6231. * {@link DateTime#toLocaleString} format like 'Oct 14, 1983, 9:30 AM'. Only 12-hour if the locale is.
  6232. * @type {Object}
  6233. */
  6234. static get DATETIME_MED() {
  6235. return DATETIME_MED;
  6236. }
  6237. /**
  6238. * {@link DateTime#toLocaleString} format like 'Oct 14, 1983, 9:30:33 AM'. Only 12-hour if the locale is.
  6239. * @type {Object}
  6240. */
  6241. static get DATETIME_MED_WITH_SECONDS() {
  6242. return DATETIME_MED_WITH_SECONDS;
  6243. }
  6244. /**
  6245. * {@link DateTime#toLocaleString} format like 'Fri, 14 Oct 1983, 9:30 AM'. Only 12-hour if the locale is.
  6246. * @type {Object}
  6247. */
  6248. static get DATETIME_MED_WITH_WEEKDAY() {
  6249. return DATETIME_MED_WITH_WEEKDAY;
  6250. }
  6251. /**
  6252. * {@link DateTime#toLocaleString} format like 'October 14, 1983, 9:30 AM EDT'. Only 12-hour if the locale is.
  6253. * @type {Object}
  6254. */
  6255. static get DATETIME_FULL() {
  6256. return DATETIME_FULL;
  6257. }
  6258. /**
  6259. * {@link DateTime#toLocaleString} format like 'October 14, 1983, 9:30:33 AM EDT'. Only 12-hour if the locale is.
  6260. * @type {Object}
  6261. */
  6262. static get DATETIME_FULL_WITH_SECONDS() {
  6263. return DATETIME_FULL_WITH_SECONDS;
  6264. }
  6265. /**
  6266. * {@link DateTime#toLocaleString} format like 'Friday, October 14, 1983, 9:30 AM Eastern Daylight Time'. Only 12-hour if the locale is.
  6267. * @type {Object}
  6268. */
  6269. static get DATETIME_HUGE() {
  6270. return DATETIME_HUGE;
  6271. }
  6272. /**
  6273. * {@link DateTime#toLocaleString} format like 'Friday, October 14, 1983, 9:30:33 AM Eastern Daylight Time'. Only 12-hour if the locale is.
  6274. * @type {Object}
  6275. */
  6276. static get DATETIME_HUGE_WITH_SECONDS() {
  6277. return DATETIME_HUGE_WITH_SECONDS;
  6278. }
  6279. }
  6280. /**
  6281. * @private
  6282. */
  6283. function friendlyDateTime(dateTimeish) {
  6284. if (DateTime.isDateTime(dateTimeish)) {
  6285. return dateTimeish;
  6286. } else if (dateTimeish && dateTimeish.valueOf && isNumber(dateTimeish.valueOf())) {
  6287. return DateTime.fromJSDate(dateTimeish);
  6288. } else if (dateTimeish && typeof dateTimeish === "object") {
  6289. return DateTime.fromObject(dateTimeish);
  6290. } else {
  6291. throw new InvalidArgumentError(`Unknown datetime argument: ${dateTimeish}, of type ${typeof dateTimeish}`);
  6292. }
  6293. }
  6294. const VERSION = "3.0.4";
  6295. exports.DateTime = DateTime;
  6296. exports.Duration = Duration;
  6297. exports.FixedOffsetZone = FixedOffsetZone;
  6298. exports.IANAZone = IANAZone;
  6299. exports.Info = Info;
  6300. exports.Interval = Interval;
  6301. exports.InvalidZone = InvalidZone;
  6302. exports.Settings = Settings;
  6303. exports.SystemZone = SystemZone;
  6304. exports.VERSION = VERSION;
  6305. exports.Zone = Zone;
  6306. //# sourceMappingURL=luxon.js.map