luxon.js 215 KB

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