Node-Red configuration
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

luxon.js 249KB

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