luxon.js 214 KB

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