Software zum Installieren eines Smart-Mirror Frameworks , zum Nutzen von hochschulrelevanten Informationen, auf einem Raspberry-Pi.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

luxon.js 214KB

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