luxon.mjs 256 KB

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