luxon.js 256 KB

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