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

luxon.js 249KB

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