DateTimeParse.cs 248 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Diagnostics;
  5. using System.Globalization;
  6. using System.Runtime.CompilerServices;
  7. using System.Text;
  8. namespace System
  9. {
  10. internal static class DateTimeParse
  11. {
  12. internal const int MaxDateTimeNumberDigits = 8;
  13. internal delegate bool MatchNumberDelegate(ref __DTString str, int digitLen, out int result);
  14. internal static MatchNumberDelegate m_hebrewNumberParser = new MatchNumberDelegate(DateTimeParse.MatchHebrewDigits);
  15. internal static DateTime ParseExact(ReadOnlySpan<char> s, ReadOnlySpan<char> format, DateTimeFormatInfo dtfi, DateTimeStyles style)
  16. {
  17. DateTimeResult result = new DateTimeResult(); // The buffer to store the parsing result.
  18. result.Init(s);
  19. if (TryParseExact(s, format, dtfi, style, ref result))
  20. {
  21. return result.parsedDate;
  22. }
  23. else
  24. {
  25. throw GetDateTimeParseException(ref result);
  26. }
  27. }
  28. internal static DateTime ParseExact(ReadOnlySpan<char> s, ReadOnlySpan<char> format, DateTimeFormatInfo dtfi, DateTimeStyles style, out TimeSpan offset)
  29. {
  30. DateTimeResult result = new DateTimeResult(); // The buffer to store the parsing result.
  31. offset = TimeSpan.Zero;
  32. result.Init(s);
  33. result.flags |= ParseFlags.CaptureOffset;
  34. if (TryParseExact(s, format, dtfi, style, ref result))
  35. {
  36. offset = result.timeZoneOffset;
  37. return result.parsedDate;
  38. }
  39. else
  40. {
  41. throw GetDateTimeParseException(ref result);
  42. }
  43. }
  44. internal static bool TryParseExact(ReadOnlySpan<char> s, ReadOnlySpan<char> format, DateTimeFormatInfo dtfi, DateTimeStyles style, out DateTime result)
  45. {
  46. result = DateTime.MinValue;
  47. DateTimeResult resultData = new DateTimeResult(); // The buffer to store the parsing result.
  48. resultData.Init(s);
  49. if (TryParseExact(s, format, dtfi, style, ref resultData))
  50. {
  51. result = resultData.parsedDate;
  52. return true;
  53. }
  54. return false;
  55. }
  56. internal static bool TryParseExact(ReadOnlySpan<char> s, ReadOnlySpan<char> format, DateTimeFormatInfo dtfi, DateTimeStyles style, out DateTime result, out TimeSpan offset)
  57. {
  58. result = DateTime.MinValue;
  59. offset = TimeSpan.Zero;
  60. DateTimeResult resultData = new DateTimeResult(); // The buffer to store the parsing result.
  61. resultData.Init(s);
  62. resultData.flags |= ParseFlags.CaptureOffset;
  63. if (TryParseExact(s, format, dtfi, style, ref resultData))
  64. {
  65. result = resultData.parsedDate;
  66. offset = resultData.timeZoneOffset;
  67. return true;
  68. }
  69. return false;
  70. }
  71. internal static bool TryParseExact(ReadOnlySpan<char> s, ReadOnlySpan<char> format, DateTimeFormatInfo dtfi, DateTimeStyles style, ref DateTimeResult result)
  72. {
  73. if (s.Length == 0)
  74. {
  75. result.SetFailure(ParseFailureKind.FormatWithParameter, nameof(SR.Format_BadDateTime));
  76. return false;
  77. }
  78. if (format.Length == 0)
  79. {
  80. result.SetBadFormatSpecifierFailure();
  81. return false;
  82. }
  83. Debug.Assert(dtfi != null, "dtfi == null");
  84. return DoStrictParse(s, format, style, dtfi, ref result);
  85. }
  86. internal static DateTime ParseExactMultiple(ReadOnlySpan<char> s, string[] formats,
  87. DateTimeFormatInfo dtfi, DateTimeStyles style)
  88. {
  89. DateTimeResult result = new DateTimeResult(); // The buffer to store the parsing result.
  90. result.Init(s);
  91. if (TryParseExactMultiple(s, formats, dtfi, style, ref result))
  92. {
  93. return result.parsedDate;
  94. }
  95. else
  96. {
  97. throw GetDateTimeParseException(ref result);
  98. }
  99. }
  100. internal static DateTime ParseExactMultiple(ReadOnlySpan<char> s, string[] formats,
  101. DateTimeFormatInfo dtfi, DateTimeStyles style, out TimeSpan offset)
  102. {
  103. DateTimeResult result = new DateTimeResult(); // The buffer to store the parsing result.
  104. offset = TimeSpan.Zero;
  105. result.Init(s);
  106. result.flags |= ParseFlags.CaptureOffset;
  107. if (TryParseExactMultiple(s, formats, dtfi, style, ref result))
  108. {
  109. offset = result.timeZoneOffset;
  110. return result.parsedDate;
  111. }
  112. else
  113. {
  114. throw GetDateTimeParseException(ref result);
  115. }
  116. }
  117. internal static bool TryParseExactMultiple(ReadOnlySpan<char> s, string[] formats,
  118. DateTimeFormatInfo dtfi, DateTimeStyles style, out DateTime result, out TimeSpan offset)
  119. {
  120. result = DateTime.MinValue;
  121. offset = TimeSpan.Zero;
  122. DateTimeResult resultData = new DateTimeResult(); // The buffer to store the parsing result.
  123. resultData.Init(s);
  124. resultData.flags |= ParseFlags.CaptureOffset;
  125. if (TryParseExactMultiple(s, formats, dtfi, style, ref resultData))
  126. {
  127. result = resultData.parsedDate;
  128. offset = resultData.timeZoneOffset;
  129. return true;
  130. }
  131. return false;
  132. }
  133. internal static bool TryParseExactMultiple(ReadOnlySpan<char> s, string[] formats,
  134. DateTimeFormatInfo dtfi, DateTimeStyles style, out DateTime result)
  135. {
  136. result = DateTime.MinValue;
  137. DateTimeResult resultData = new DateTimeResult(); // The buffer to store the parsing result.
  138. resultData.Init(s);
  139. if (TryParseExactMultiple(s, formats, dtfi, style, ref resultData))
  140. {
  141. result = resultData.parsedDate;
  142. return true;
  143. }
  144. return false;
  145. }
  146. internal static bool TryParseExactMultiple(ReadOnlySpan<char> s, string[] formats,
  147. DateTimeFormatInfo dtfi, DateTimeStyles style, ref DateTimeResult result)
  148. {
  149. if (formats == null)
  150. {
  151. result.SetFailure(ParseFailureKind.ArgumentNull, nameof(SR.ArgumentNull_String), null, nameof(formats));
  152. return false;
  153. }
  154. if (s.Length == 0)
  155. {
  156. result.SetFailure(ParseFailureKind.FormatWithParameter, nameof(SR.Format_BadDateTime));
  157. return false;
  158. }
  159. if (formats.Length == 0)
  160. {
  161. result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_NoFormatSpecifier));
  162. return false;
  163. }
  164. Debug.Assert(dtfi != null, "dtfi == null");
  165. //
  166. // Do a loop through the provided formats and see if we can parse successfully in
  167. // one of the formats.
  168. //
  169. for (int i = 0; i < formats.Length; i++)
  170. {
  171. if (formats[i] == null || formats[i].Length == 0)
  172. {
  173. result.SetBadFormatSpecifierFailure();
  174. return false;
  175. }
  176. // Create a new result each time to ensure the runs are independent. Carry through
  177. // flags from the caller and return the result.
  178. DateTimeResult innerResult = new DateTimeResult(); // The buffer to store the parsing result.
  179. innerResult.Init(s);
  180. innerResult.flags = result.flags;
  181. if (TryParseExact(s, formats[i], dtfi, style, ref innerResult))
  182. {
  183. result.parsedDate = innerResult.parsedDate;
  184. result.timeZoneOffset = innerResult.timeZoneOffset;
  185. return (true);
  186. }
  187. }
  188. result.SetBadDateTimeFailure();
  189. return (false);
  190. }
  191. ////////////////////////////////////////////////////////////////////////////
  192. // Date Token Types
  193. //
  194. // Following is the set of tokens that can be generated from a date
  195. // string. Notice that the legal set of trailing separators have been
  196. // folded in with the date number, and month name tokens. This set
  197. // of tokens is chosen to reduce the number of date parse states.
  198. //
  199. ////////////////////////////////////////////////////////////////////////////
  200. internal enum DTT : int
  201. {
  202. End = 0, // '\0'
  203. NumEnd = 1, // Num[ ]*[\0]
  204. NumAmpm = 2, // Num[ ]+AmPm
  205. NumSpace = 3, // Num[ ]+^[Dsep|Tsep|'0\']
  206. NumDatesep = 4, // Num[ ]*Dsep
  207. NumTimesep = 5, // Num[ ]*Tsep
  208. MonthEnd = 6, // Month[ ]*'\0'
  209. MonthSpace = 7, // Month[ ]+^[Dsep|Tsep|'\0']
  210. MonthDatesep = 8, // Month[ ]*Dsep
  211. NumDatesuff = 9, // Month[ ]*DSuff
  212. NumTimesuff = 10, // Month[ ]*TSuff
  213. DayOfWeek = 11, // Day of week name
  214. YearSpace = 12, // Year+^[Dsep|Tsep|'0\']
  215. YearDateSep = 13, // Year+Dsep
  216. YearEnd = 14, // Year+['\0']
  217. TimeZone = 15, // timezone name
  218. Era = 16, // era name
  219. NumUTCTimeMark = 17, // Num + 'Z'
  220. // When you add a new token which will be in the
  221. // state table, add it after NumLocalTimeMark.
  222. Unk = 18, // unknown
  223. NumLocalTimeMark = 19, // Num + 'T'
  224. Max = 20, // marker
  225. }
  226. internal enum TM
  227. {
  228. NotSet = -1,
  229. AM = 0,
  230. PM = 1,
  231. }
  232. ////////////////////////////////////////////////////////////////////////////
  233. //
  234. // DateTime parsing state enumeration (DS.*)
  235. //
  236. ////////////////////////////////////////////////////////////////////////////
  237. internal enum DS
  238. {
  239. BEGIN = 0,
  240. N = 1, // have one number
  241. NN = 2, // have two numbers
  242. // The following are known to be part of a date
  243. D_Nd = 3, // date string: have number followed by date separator
  244. D_NN = 4, // date string: have two numbers
  245. D_NNd = 5, // date string: have two numbers followed by date separator
  246. D_M = 6, // date string: have a month
  247. D_MN = 7, // date string: have a month and a number
  248. D_NM = 8, // date string: have a number and a month
  249. D_MNd = 9, // date string: have a month and number followed by date separator
  250. D_NDS = 10, // date string: have one number followed a date suffix.
  251. D_Y = 11, // date string: have a year.
  252. D_YN = 12, // date string: have a year and a number
  253. D_YNd = 13, // date string: have a year and a number and a date separator
  254. D_YM = 14, // date string: have a year and a month
  255. D_YMd = 15, // date string: have a year and a month and a date separator
  256. D_S = 16, // have numbers followed by a date suffix.
  257. T_S = 17, // have numbers followed by a time suffix.
  258. // The following are known to be part of a time
  259. T_Nt = 18, // have num followed by time separator
  260. T_NNt = 19, // have two numbers followed by time separator
  261. ERROR = 20,
  262. // The following are terminal states. These all have an action
  263. // associated with them; and transition back to BEGIN.
  264. DX_NN = 21, // day from two numbers
  265. DX_NNN = 22, // day from three numbers
  266. DX_MN = 23, // day from month and one number
  267. DX_NM = 24, // day from month and one number
  268. DX_MNN = 25, // day from month and two numbers
  269. DX_DS = 26, // a set of date suffixed numbers.
  270. DX_DSN = 27, // day from date suffixes and one number.
  271. DX_NDS = 28, // day from one number and date suffixes .
  272. DX_NNDS = 29, // day from one number and date suffixes .
  273. DX_YNN = 30, // date string: have a year and two number
  274. DX_YMN = 31, // date string: have a year, a month, and a number.
  275. DX_YN = 32, // date string: have a year and one number
  276. DX_YM = 33, // date string: have a year, a month.
  277. TX_N = 34, // time from one number (must have ampm)
  278. TX_NN = 35, // time from two numbers
  279. TX_NNN = 36, // time from three numbers
  280. TX_TS = 37, // a set of time suffixed numbers.
  281. DX_NNY = 38,
  282. }
  283. ////////////////////////////////////////////////////////////////////////////
  284. //
  285. // NOTE: The following state machine table is dependent on the order of the
  286. // DS and DTT enumerations.
  287. //
  288. // For each non terminal state, the following table defines the next state
  289. // for each given date token type.
  290. //
  291. ////////////////////////////////////////////////////////////////////////////
  292. // End NumEnd NumAmPm NumSpace NumDaySep NumTimesep MonthEnd MonthSpace MonthDSep NumDateSuff NumTimeSuff DayOfWeek YearSpace YearDateSep YearEnd TimeZone Era UTCTimeMark
  293. private static DS[][] dateParsingStates = {
  294. // DS.BEGIN // DS.BEGIN
  295. new DS[] { DS.BEGIN, DS.ERROR, DS.TX_N, DS.N, DS.D_Nd, DS.T_Nt, DS.ERROR, DS.D_M, DS.D_M, DS.D_S, DS.T_S, DS.BEGIN, DS.D_Y, DS.D_Y, DS.ERROR, DS.BEGIN, DS.BEGIN, DS.ERROR},
  296. // DS.N // DS.N
  297. new DS[] { DS.ERROR, DS.DX_NN, DS.ERROR, DS.NN, DS.D_NNd, DS.ERROR, DS.DX_NM, DS.D_NM, DS.D_MNd, DS.D_NDS, DS.ERROR, DS.N, DS.D_YN, DS.D_YNd, DS.DX_YN, DS.N, DS.N, DS.ERROR},
  298. // DS.NN // DS.NN
  299. new DS[] { DS.DX_NN, DS.DX_NNN, DS.TX_N, DS.DX_NNN, DS.ERROR, DS.T_Nt, DS.DX_MNN, DS.DX_MNN, DS.ERROR, DS.ERROR, DS.T_S, DS.NN, DS.DX_NNY, DS.ERROR, DS.DX_NNY, DS.NN, DS.NN, DS.ERROR},
  300. // DS.D_Nd // DS.D_Nd
  301. new DS[] { DS.ERROR, DS.DX_NN, DS.ERROR, DS.D_NN, DS.D_NNd, DS.ERROR, DS.DX_NM, DS.D_MN, DS.D_MNd, DS.ERROR, DS.ERROR, DS.D_Nd, DS.D_YN, DS.D_YNd, DS.DX_YN, DS.ERROR, DS.D_Nd, DS.ERROR},
  302. // DS.D_NN // DS.D_NN
  303. new DS[] { DS.DX_NN, DS.DX_NNN, DS.TX_N, DS.DX_NNN, DS.ERROR, DS.T_Nt, DS.DX_MNN, DS.DX_MNN, DS.ERROR, DS.DX_DS, DS.T_S, DS.D_NN, DS.DX_NNY, DS.ERROR, DS.DX_NNY, DS.ERROR, DS.D_NN, DS.ERROR},
  304. // DS.D_NNd // DS.D_NNd
  305. new DS[] { DS.ERROR, DS.DX_NNN, DS.DX_NNN, DS.DX_NNN, DS.ERROR, DS.ERROR, DS.DX_MNN, DS.DX_MNN, DS.ERROR, DS.DX_DS, DS.ERROR, DS.D_NNd, DS.DX_NNY, DS.ERROR, DS.DX_NNY, DS.ERROR, DS.D_NNd, DS.ERROR},
  306. // DS.D_M // DS.D_M
  307. new DS[] { DS.ERROR, DS.DX_MN, DS.ERROR, DS.D_MN, DS.D_MNd, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_M, DS.D_YM, DS.D_YMd, DS.DX_YM, DS.ERROR, DS.D_M, DS.ERROR},
  308. // DS.D_MN // DS.D_MN
  309. new DS[] { DS.DX_MN, DS.DX_MNN, DS.DX_MNN, DS.DX_MNN, DS.ERROR, DS.T_Nt, DS.ERROR, DS.ERROR, DS.ERROR, DS.DX_DS, DS.T_S, DS.D_MN, DS.DX_YMN, DS.ERROR, DS.DX_YMN, DS.ERROR, DS.D_MN, DS.ERROR},
  310. // DS.D_NM // DS.D_NM
  311. new DS[] { DS.DX_NM, DS.DX_MNN, DS.DX_MNN, DS.DX_MNN, DS.ERROR, DS.T_Nt, DS.ERROR, DS.ERROR, DS.ERROR, DS.DX_DS, DS.T_S, DS.D_NM, DS.DX_YMN, DS.ERROR, DS.DX_YMN, DS.ERROR, DS.D_NM, DS.ERROR},
  312. // DS.D_MNd // DS.D_MNd
  313. new DS[] { DS.ERROR, DS.DX_MNN, DS.ERROR, DS.DX_MNN, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_MNd, DS.DX_YMN, DS.ERROR, DS.DX_YMN, DS.ERROR, DS.D_MNd, DS.ERROR},
  314. // DS.D_NDS, // DS.D_NDS,
  315. new DS[] { DS.DX_NDS,DS.DX_NNDS, DS.DX_NNDS, DS.DX_NNDS, DS.ERROR, DS.T_Nt, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_NDS, DS.T_S, DS.D_NDS, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_NDS, DS.ERROR},
  316. // DS.D_Y // DS.D_Y
  317. new DS[] { DS.ERROR, DS.DX_YN, DS.ERROR, DS.D_YN, DS.D_YNd, DS.ERROR, DS.DX_YM, DS.D_YM, DS.D_YMd, DS.D_YM, DS.ERROR, DS.D_Y, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_Y, DS.ERROR},
  318. // DS.D_YN // DS.D_YN
  319. new DS[] { DS.DX_YN, DS.DX_YNN, DS.DX_YNN, DS.DX_YNN, DS.ERROR, DS.ERROR, DS.DX_YMN, DS.DX_YMN, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_YN, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_YN, DS.ERROR},
  320. // DS.D_YNd // DS.D_YNd
  321. new DS[] { DS.ERROR, DS.DX_YNN, DS.DX_YNN, DS.DX_YNN, DS.ERROR, DS.ERROR, DS.DX_YMN, DS.DX_YMN, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_YN, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_YN, DS.ERROR},
  322. // DS.D_YM // DS.D_YM
  323. new DS[] { DS.DX_YM, DS.DX_YMN, DS.DX_YMN, DS.DX_YMN, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_YM, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_YM, DS.ERROR},
  324. // DS.D_YMd // DS.D_YMd
  325. new DS[] { DS.ERROR, DS.DX_YMN, DS.DX_YMN, DS.DX_YMN, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_YM, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_YM, DS.ERROR},
  326. // DS.D_S // DS.D_S
  327. new DS[] { DS.DX_DS, DS.DX_DSN, DS.TX_N, DS.T_Nt, DS.ERROR, DS.T_Nt, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_S, DS.T_S, DS.D_S, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_S, DS.ERROR},
  328. // DS.T_S // DS.T_S
  329. new DS[] { DS.TX_TS, DS.TX_TS, DS.TX_TS, DS.T_Nt, DS.D_Nd, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_S, DS.T_S, DS.T_S, DS.ERROR, DS.ERROR, DS.ERROR, DS.T_S, DS.T_S, DS.ERROR},
  330. // DS.T_Nt // DS.T_Nt
  331. new DS[] { DS.ERROR, DS.TX_NN, DS.TX_NN, DS.TX_NN, DS.ERROR, DS.T_NNt, DS.DX_NM, DS.D_NM, DS.ERROR, DS.ERROR, DS.T_S, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.T_Nt, DS.T_Nt, DS.TX_NN},
  332. // DS.T_NNt // DS.T_NNt
  333. new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.T_S, DS.T_NNt, DS.ERROR, DS.ERROR, DS.ERROR, DS.T_NNt, DS.T_NNt, DS.TX_NNN},
  334. };
  335. // End NumEnd NumAmPm NumSpace NumDaySep NumTimesep MonthEnd MonthSpace MonthDSep NumDateSuff NumTimeSuff DayOfWeek YearSpace YearDateSep YearEnd TimeZone Era UTCMark
  336. internal const string GMTName = "GMT";
  337. internal const string ZuluName = "Z";
  338. //
  339. // Search from the index of str at str.Index to see if the target string exists in the str.
  340. //
  341. private static bool MatchWord(ref __DTString str, string target)
  342. {
  343. if (target.Length > (str.Value.Length - str.Index))
  344. {
  345. return false;
  346. }
  347. if (str.CompareInfo.Compare(str.Value.Slice(str.Index, target.Length), target, CompareOptions.IgnoreCase) != 0)
  348. {
  349. return (false);
  350. }
  351. int nextCharIndex = str.Index + target.Length;
  352. if (nextCharIndex < str.Value.Length)
  353. {
  354. char nextCh = str.Value[nextCharIndex];
  355. if (char.IsLetter(nextCh))
  356. {
  357. return (false);
  358. }
  359. }
  360. str.Index = nextCharIndex;
  361. if (str.Index < str.Length)
  362. {
  363. str.m_current = str.Value[str.Index];
  364. }
  365. return (true);
  366. }
  367. //
  368. // Check the word at the current index to see if it matches GMT name or Zulu name.
  369. //
  370. private static bool GetTimeZoneName(ref __DTString str)
  371. {
  372. if (MatchWord(ref str, GMTName))
  373. {
  374. return (true);
  375. }
  376. if (MatchWord(ref str, ZuluName))
  377. {
  378. return (true);
  379. }
  380. return (false);
  381. }
  382. internal static bool IsDigit(char ch) => (uint)(ch - '0') <= 9;
  383. /*=================================ParseFraction==========================
  384. **Action: Starting at the str.Index, which should be a decimal symbol.
  385. ** if the current character is a digit, parse the remaining
  386. ** numbers as fraction. For example, if the sub-string starting at str.Index is "123", then
  387. ** the method will return 0.123
  388. **Returns: The fraction number.
  389. **Arguments:
  390. ** str the parsing string
  391. **Exceptions:
  392. ============================================================================*/
  393. private static bool ParseFraction(ref __DTString str, out double result)
  394. {
  395. result = 0;
  396. double decimalBase = 0.1;
  397. int digits = 0;
  398. char ch;
  399. while (str.GetNext()
  400. && IsDigit(ch = str.m_current))
  401. {
  402. result += (ch - '0') * decimalBase;
  403. decimalBase *= 0.1;
  404. digits++;
  405. }
  406. return (digits > 0);
  407. }
  408. /*=================================ParseTimeZone==========================
  409. **Action: Parse the timezone offset in the following format:
  410. ** "+8", "+08", "+0800", "+0800"
  411. ** This method is used by DateTime.Parse().
  412. **Returns: The TimeZone offset.
  413. **Arguments:
  414. ** str the parsing string
  415. **Exceptions:
  416. ** FormatException if invalid timezone format is found.
  417. ============================================================================*/
  418. private static bool ParseTimeZone(ref __DTString str, ref TimeSpan result)
  419. {
  420. // The hour/minute offset for timezone.
  421. int hourOffset = 0;
  422. int minuteOffset = 0;
  423. DTSubString sub;
  424. // Consume the +/- character that has already been read
  425. sub = str.GetSubString();
  426. if (sub.length != 1)
  427. {
  428. return false;
  429. }
  430. char offsetChar = sub[0];
  431. if (offsetChar != '+' && offsetChar != '-')
  432. {
  433. return false;
  434. }
  435. str.ConsumeSubString(sub);
  436. sub = str.GetSubString();
  437. if (sub.type != DTSubStringType.Number)
  438. {
  439. return false;
  440. }
  441. int value = sub.value;
  442. int length = sub.length;
  443. if (length == 1 || length == 2)
  444. {
  445. // Parsing "+8" or "+08"
  446. hourOffset = value;
  447. str.ConsumeSubString(sub);
  448. // See if we have minutes
  449. sub = str.GetSubString();
  450. if (sub.length == 1 && sub[0] == ':')
  451. {
  452. // Parsing "+8:00" or "+08:00"
  453. str.ConsumeSubString(sub);
  454. sub = str.GetSubString();
  455. if (sub.type != DTSubStringType.Number || sub.length < 1 || sub.length > 2)
  456. {
  457. return false;
  458. }
  459. minuteOffset = sub.value;
  460. str.ConsumeSubString(sub);
  461. }
  462. }
  463. else if (length == 3 || length == 4)
  464. {
  465. // Parsing "+800" or "+0800"
  466. hourOffset = value / 100;
  467. minuteOffset = value % 100;
  468. str.ConsumeSubString(sub);
  469. }
  470. else
  471. {
  472. // Wrong number of digits
  473. return false;
  474. }
  475. Debug.Assert(hourOffset >= 0 && hourOffset <= 99, "hourOffset >= 0 && hourOffset <= 99");
  476. Debug.Assert(minuteOffset >= 0 && minuteOffset <= 99, "minuteOffset >= 0 && minuteOffset <= 99");
  477. if (minuteOffset < 0 || minuteOffset >= 60)
  478. {
  479. return false;
  480. }
  481. result = new TimeSpan(hourOffset, minuteOffset, 0);
  482. if (offsetChar == '-')
  483. {
  484. result = result.Negate();
  485. }
  486. return true;
  487. }
  488. // This is the helper function to handle timezone in string in the format like +/-0800
  489. private static bool HandleTimeZone(ref __DTString str, ref DateTimeResult result)
  490. {
  491. if ((str.Index < str.Length - 1))
  492. {
  493. char nextCh = str.Value[str.Index];
  494. // Skip whitespace, but don't update the index unless we find a time zone marker
  495. int whitespaceCount = 0;
  496. while (char.IsWhiteSpace(nextCh) && str.Index + whitespaceCount < str.Length - 1)
  497. {
  498. whitespaceCount++;
  499. nextCh = str.Value[str.Index + whitespaceCount];
  500. }
  501. if (nextCh == '+' || nextCh == '-')
  502. {
  503. str.Index += whitespaceCount;
  504. if ((result.flags & ParseFlags.TimeZoneUsed) != 0)
  505. {
  506. // Should not have two timezone offsets.
  507. result.SetBadDateTimeFailure();
  508. return false;
  509. }
  510. result.flags |= ParseFlags.TimeZoneUsed;
  511. if (!ParseTimeZone(ref str, ref result.timeZoneOffset))
  512. {
  513. result.SetBadDateTimeFailure();
  514. return false;
  515. }
  516. }
  517. }
  518. return true;
  519. }
  520. //
  521. // This is the lexer. Check the character at the current index, and put the found token in dtok and
  522. // some raw date/time information in raw.
  523. //
  524. private static bool Lex(DS dps, ref __DTString str, ref DateTimeToken dtok, ref DateTimeRawInfo raw, ref DateTimeResult result, ref DateTimeFormatInfo dtfi, DateTimeStyles styles)
  525. {
  526. TokenType tokenType;
  527. int tokenValue;
  528. int indexBeforeSeparator;
  529. char charBeforeSeparator;
  530. TokenType sep;
  531. dtok.dtt = DTT.Unk; // Assume the token is unkown.
  532. str.GetRegularToken(out tokenType, out tokenValue, dtfi);
  533. #if _LOGGING
  534. if (_tracingEnabled)
  535. {
  536. Trace($"Lex({Hex(str.Value)})\tpos:{str.Index}({Hex(str.m_current)}), {tokenType}, DS.{dps}");
  537. }
  538. #endif // _LOGGING
  539. // Look at the regular token.
  540. switch (tokenType)
  541. {
  542. case TokenType.NumberToken:
  543. case TokenType.YearNumberToken:
  544. if (raw.numCount == 3 || tokenValue == -1)
  545. {
  546. result.SetBadDateTimeFailure();
  547. LexTraceExit("0010", dps);
  548. return false;
  549. }
  550. //
  551. // This is a digit.
  552. //
  553. // If the previous parsing state is DS.T_NNt (like 12:01), and we got another number,
  554. // so we will have a terminal state DS.TX_NNN (like 12:01:02).
  555. // If the previous parsing state is DS.T_Nt (like 12:), and we got another number,
  556. // so we will have a terminal state DS.TX_NN (like 12:01).
  557. //
  558. // Look ahead to see if the following character is a decimal point or timezone offset.
  559. // This enables us to parse time in the forms of:
  560. // "11:22:33.1234" or "11:22:33-08".
  561. if (dps == DS.T_NNt)
  562. {
  563. if ((str.Index < str.Length - 1))
  564. {
  565. char nextCh = str.Value[str.Index];
  566. if (nextCh == '.')
  567. {
  568. // While ParseFraction can fail, it just means that there were no digits after
  569. // the dot. In this case ParseFraction just removes the dot. This is actually
  570. // valid for cultures like Albanian, that join the time marker to the time with
  571. // with a dot: e.g. "9:03.MD"
  572. ParseFraction(ref str, out raw.fraction);
  573. }
  574. }
  575. }
  576. if (dps == DS.T_NNt || dps == DS.T_Nt)
  577. {
  578. if ((str.Index < str.Length - 1))
  579. {
  580. if (false == HandleTimeZone(ref str, ref result))
  581. {
  582. LexTraceExit("0020 (value like \"12:01\" or \"12:\" followed by a non-TZ number", dps);
  583. return false;
  584. }
  585. }
  586. }
  587. dtok.num = tokenValue;
  588. if (tokenType == TokenType.YearNumberToken)
  589. {
  590. if (raw.year == -1)
  591. {
  592. raw.year = tokenValue;
  593. //
  594. // If we have number which has 3 or more digits (like "001" or "0001"),
  595. // we assume this number is a year. Save the current raw.numCount in
  596. // raw.year.
  597. //
  598. switch (sep = str.GetSeparatorToken(dtfi, out indexBeforeSeparator, out charBeforeSeparator))
  599. {
  600. case TokenType.SEP_End:
  601. dtok.dtt = DTT.YearEnd;
  602. break;
  603. case TokenType.SEP_Am:
  604. case TokenType.SEP_Pm:
  605. if (raw.timeMark == TM.NotSet)
  606. {
  607. raw.timeMark = (sep == TokenType.SEP_Am ? TM.AM : TM.PM);
  608. dtok.dtt = DTT.YearSpace;
  609. }
  610. else
  611. {
  612. result.SetBadDateTimeFailure();
  613. LexTraceExit("0030 (TM.AM/TM.PM Happened more than 1x)", dps);
  614. }
  615. break;
  616. case TokenType.SEP_Space:
  617. dtok.dtt = DTT.YearSpace;
  618. break;
  619. case TokenType.SEP_Date:
  620. dtok.dtt = DTT.YearDateSep;
  621. break;
  622. case TokenType.SEP_Time:
  623. if (!raw.hasSameDateAndTimeSeparators)
  624. {
  625. result.SetBadDateTimeFailure();
  626. LexTraceExit("0040 (Invalid separator after number)", dps);
  627. return false;
  628. }
  629. // we have the date and time separators are same and getting a year number, then change the token to YearDateSep as
  630. // we are sure we are not parsing time.
  631. dtok.dtt = DTT.YearDateSep;
  632. break;
  633. case TokenType.SEP_DateOrOffset:
  634. // The separator is either a date separator or the start of a time zone offset. If the token will complete the date then
  635. // process just the number and roll back the index so that the outer loop can attempt to parse the time zone offset.
  636. if ((dateParsingStates[(int)dps][(int)DTT.YearDateSep] == DS.ERROR)
  637. && (dateParsingStates[(int)dps][(int)DTT.YearSpace] > DS.ERROR))
  638. {
  639. str.Index = indexBeforeSeparator;
  640. str.m_current = charBeforeSeparator;
  641. dtok.dtt = DTT.YearSpace;
  642. }
  643. else
  644. {
  645. dtok.dtt = DTT.YearDateSep;
  646. }
  647. break;
  648. case TokenType.SEP_YearSuff:
  649. case TokenType.SEP_MonthSuff:
  650. case TokenType.SEP_DaySuff:
  651. dtok.dtt = DTT.NumDatesuff;
  652. dtok.suffix = sep;
  653. break;
  654. case TokenType.SEP_HourSuff:
  655. case TokenType.SEP_MinuteSuff:
  656. case TokenType.SEP_SecondSuff:
  657. dtok.dtt = DTT.NumTimesuff;
  658. dtok.suffix = sep;
  659. break;
  660. default:
  661. // Invalid separator after number number.
  662. result.SetBadDateTimeFailure();
  663. LexTraceExit("0040 (Invalid separator after number)", dps);
  664. return false;
  665. }
  666. //
  667. // Found the token already. Return now.
  668. //
  669. LexTraceExit("0050 (success)", dps);
  670. return true;
  671. }
  672. result.SetBadDateTimeFailure();
  673. LexTraceExit("0060", dps);
  674. return false;
  675. }
  676. switch (sep = str.GetSeparatorToken(dtfi, out indexBeforeSeparator, out charBeforeSeparator))
  677. {
  678. //
  679. // Note here we check if the numCount is less than three.
  680. // When we have more than three numbers, it will be caught as error in the state machine.
  681. //
  682. case TokenType.SEP_End:
  683. dtok.dtt = DTT.NumEnd;
  684. raw.AddNumber(dtok.num);
  685. break;
  686. case TokenType.SEP_Am:
  687. case TokenType.SEP_Pm:
  688. if (raw.timeMark == TM.NotSet)
  689. {
  690. raw.timeMark = (sep == TokenType.SEP_Am ? TM.AM : TM.PM);
  691. dtok.dtt = DTT.NumAmpm;
  692. // Fix AM/PM parsing case, e.g. "1/10 5 AM"
  693. if (dps == DS.D_NN)
  694. {
  695. if (!ProcessTerminalState(DS.DX_NN, ref str, ref result, ref styles, ref raw, dtfi))
  696. {
  697. return false;
  698. }
  699. }
  700. raw.AddNumber(dtok.num);
  701. }
  702. else
  703. {
  704. result.SetBadDateTimeFailure();
  705. break;
  706. }
  707. if (dps == DS.T_NNt || dps == DS.T_Nt)
  708. {
  709. if (false == HandleTimeZone(ref str, ref result))
  710. {
  711. LexTraceExit("0070 (HandleTimeZone returned false)", dps);
  712. return false;
  713. }
  714. }
  715. break;
  716. case TokenType.SEP_Space:
  717. dtok.dtt = DTT.NumSpace;
  718. raw.AddNumber(dtok.num);
  719. break;
  720. case TokenType.SEP_Date:
  721. dtok.dtt = DTT.NumDatesep;
  722. raw.AddNumber(dtok.num);
  723. break;
  724. case TokenType.SEP_DateOrOffset:
  725. // The separator is either a date separator or the start of a time zone offset. If the token will complete the date then
  726. // process just the number and roll back the index so that the outer loop can attempt to parse the time zone offset.
  727. if ((dateParsingStates[(int)dps][(int)DTT.NumDatesep] == DS.ERROR)
  728. && (dateParsingStates[(int)dps][(int)DTT.NumSpace] > DS.ERROR))
  729. {
  730. str.Index = indexBeforeSeparator;
  731. str.m_current = charBeforeSeparator;
  732. dtok.dtt = DTT.NumSpace;
  733. }
  734. else
  735. {
  736. dtok.dtt = DTT.NumDatesep;
  737. }
  738. raw.AddNumber(dtok.num);
  739. break;
  740. case TokenType.SEP_Time:
  741. if (raw.hasSameDateAndTimeSeparators &&
  742. (dps == DS.D_Y || dps == DS.D_YN || dps == DS.D_YNd || dps == DS.D_YM || dps == DS.D_YMd))
  743. {
  744. // we are parsing a date and we have the time separator same as date separator, so we mark the token as date separator
  745. dtok.dtt = DTT.NumDatesep;
  746. raw.AddNumber(dtok.num);
  747. break;
  748. }
  749. dtok.dtt = DTT.NumTimesep;
  750. raw.AddNumber(dtok.num);
  751. break;
  752. case TokenType.SEP_YearSuff:
  753. try
  754. {
  755. dtok.num = dtfi.Calendar.ToFourDigitYear(tokenValue);
  756. }
  757. catch (ArgumentOutOfRangeException)
  758. {
  759. result.SetBadDateTimeFailure();
  760. LexTraceExit("0075 (Calendar.ToFourDigitYear failed)", dps);
  761. return false;
  762. }
  763. dtok.dtt = DTT.NumDatesuff;
  764. dtok.suffix = sep;
  765. break;
  766. case TokenType.SEP_MonthSuff:
  767. case TokenType.SEP_DaySuff:
  768. dtok.dtt = DTT.NumDatesuff;
  769. dtok.suffix = sep;
  770. break;
  771. case TokenType.SEP_HourSuff:
  772. case TokenType.SEP_MinuteSuff:
  773. case TokenType.SEP_SecondSuff:
  774. dtok.dtt = DTT.NumTimesuff;
  775. dtok.suffix = sep;
  776. break;
  777. case TokenType.SEP_LocalTimeMark:
  778. dtok.dtt = DTT.NumLocalTimeMark;
  779. raw.AddNumber(dtok.num);
  780. break;
  781. default:
  782. // Invalid separator after number number.
  783. result.SetBadDateTimeFailure();
  784. LexTraceExit("0080", dps);
  785. return false;
  786. }
  787. break;
  788. case TokenType.HebrewNumber:
  789. if (tokenValue >= 100)
  790. {
  791. // This is a year number
  792. if (raw.year == -1)
  793. {
  794. raw.year = tokenValue;
  795. //
  796. // If we have number which has 3 or more digits (like "001" or "0001"),
  797. // we assume this number is a year. Save the current raw.numCount in
  798. // raw.year.
  799. //
  800. switch (sep = str.GetSeparatorToken(dtfi, out indexBeforeSeparator, out charBeforeSeparator))
  801. {
  802. case TokenType.SEP_End:
  803. dtok.dtt = DTT.YearEnd;
  804. break;
  805. case TokenType.SEP_Space:
  806. dtok.dtt = DTT.YearSpace;
  807. break;
  808. case TokenType.SEP_DateOrOffset:
  809. // The separator is either a date separator or the start of a time zone offset. If the token will complete the date then
  810. // process just the number and roll back the index so that the outer loop can attempt to parse the time zone offset.
  811. if (dateParsingStates[(int)dps][(int)DTT.YearSpace] > DS.ERROR)
  812. {
  813. str.Index = indexBeforeSeparator;
  814. str.m_current = charBeforeSeparator;
  815. dtok.dtt = DTT.YearSpace;
  816. break;
  817. }
  818. goto default;
  819. default:
  820. // Invalid separator after number number.
  821. result.SetBadDateTimeFailure();
  822. LexTraceExit("0090", dps);
  823. return false;
  824. }
  825. }
  826. else
  827. {
  828. // Invalid separator after number number.
  829. result.SetBadDateTimeFailure();
  830. LexTraceExit("0100", dps);
  831. return false;
  832. }
  833. }
  834. else
  835. {
  836. // This is a day number
  837. dtok.num = tokenValue;
  838. raw.AddNumber(dtok.num);
  839. switch (sep = str.GetSeparatorToken(dtfi, out indexBeforeSeparator, out charBeforeSeparator))
  840. {
  841. //
  842. // Note here we check if the numCount is less than three.
  843. // When we have more than three numbers, it will be caught as error in the state machine.
  844. //
  845. case TokenType.SEP_End:
  846. dtok.dtt = DTT.NumEnd;
  847. break;
  848. case TokenType.SEP_Space:
  849. case TokenType.SEP_Date:
  850. dtok.dtt = DTT.NumDatesep;
  851. break;
  852. case TokenType.SEP_DateOrOffset:
  853. // The separator is either a date separator or the start of a time zone offset. If the token will complete the date then
  854. // process just the number and roll back the index so that the outer loop can attempt to parse the time zone offset.
  855. if ((dateParsingStates[(int)dps][(int)DTT.NumDatesep] == DS.ERROR)
  856. && (dateParsingStates[(int)dps][(int)DTT.NumSpace] > DS.ERROR))
  857. {
  858. str.Index = indexBeforeSeparator;
  859. str.m_current = charBeforeSeparator;
  860. dtok.dtt = DTT.NumSpace;
  861. }
  862. else
  863. {
  864. dtok.dtt = DTT.NumDatesep;
  865. }
  866. break;
  867. default:
  868. // Invalid separator after number number.
  869. result.SetBadDateTimeFailure();
  870. LexTraceExit("0110", dps);
  871. return false;
  872. }
  873. }
  874. break;
  875. case TokenType.DayOfWeekToken:
  876. if (raw.dayOfWeek == -1)
  877. {
  878. //
  879. // This is a day of week name.
  880. //
  881. raw.dayOfWeek = tokenValue;
  882. dtok.dtt = DTT.DayOfWeek;
  883. }
  884. else
  885. {
  886. result.SetBadDateTimeFailure();
  887. LexTraceExit("0120 (DayOfWeek seen more than 1x)", dps);
  888. return false;
  889. }
  890. break;
  891. case TokenType.MonthToken:
  892. if (raw.month == -1)
  893. {
  894. //
  895. // This is a month name
  896. //
  897. switch (sep = str.GetSeparatorToken(dtfi, out indexBeforeSeparator, out charBeforeSeparator))
  898. {
  899. case TokenType.SEP_End:
  900. dtok.dtt = DTT.MonthEnd;
  901. break;
  902. case TokenType.SEP_Space:
  903. dtok.dtt = DTT.MonthSpace;
  904. break;
  905. case TokenType.SEP_Date:
  906. dtok.dtt = DTT.MonthDatesep;
  907. break;
  908. case TokenType.SEP_Time:
  909. if (!raw.hasSameDateAndTimeSeparators)
  910. {
  911. result.SetBadDateTimeFailure();
  912. LexTraceExit("0130 (Invalid separator after month name)", dps);
  913. return false;
  914. }
  915. // we have the date and time separators are same and getting a Month name, then change the token to MonthDatesep as
  916. // we are sure we are not parsing time.
  917. dtok.dtt = DTT.MonthDatesep;
  918. break;
  919. case TokenType.SEP_DateOrOffset:
  920. // The separator is either a date separator or the start of a time zone offset. If the token will complete the date then
  921. // process just the number and roll back the index so that the outer loop can attempt to parse the time zone offset.
  922. if ((dateParsingStates[(int)dps][(int)DTT.MonthDatesep] == DS.ERROR)
  923. && (dateParsingStates[(int)dps][(int)DTT.MonthSpace] > DS.ERROR))
  924. {
  925. str.Index = indexBeforeSeparator;
  926. str.m_current = charBeforeSeparator;
  927. dtok.dtt = DTT.MonthSpace;
  928. }
  929. else
  930. {
  931. dtok.dtt = DTT.MonthDatesep;
  932. }
  933. break;
  934. default:
  935. //Invalid separator after month name
  936. result.SetBadDateTimeFailure();
  937. LexTraceExit("0130 (Invalid separator after month name)", dps);
  938. return false;
  939. }
  940. raw.month = tokenValue;
  941. }
  942. else
  943. {
  944. result.SetBadDateTimeFailure();
  945. LexTraceExit("0140 (MonthToken seen more than 1x)", dps);
  946. return false;
  947. }
  948. break;
  949. case TokenType.EraToken:
  950. if (result.era != -1)
  951. {
  952. result.era = tokenValue;
  953. dtok.dtt = DTT.Era;
  954. }
  955. else
  956. {
  957. result.SetBadDateTimeFailure();
  958. LexTraceExit("0150 (EraToken seen when result.era already set)", dps);
  959. return false;
  960. }
  961. break;
  962. case TokenType.JapaneseEraToken:
  963. // Special case for Japanese. We allow Japanese era name to be used even if the calendar is not Japanese Calendar.
  964. result.calendar = JapaneseCalendar.GetDefaultInstance();
  965. dtfi = DateTimeFormatInfo.GetJapaneseCalendarDTFI();
  966. if (result.era != -1)
  967. {
  968. result.era = tokenValue;
  969. dtok.dtt = DTT.Era;
  970. }
  971. else
  972. {
  973. result.SetBadDateTimeFailure();
  974. LexTraceExit("0160 (JapaneseEraToken seen when result.era already set)", dps);
  975. return false;
  976. }
  977. break;
  978. case TokenType.TEraToken:
  979. result.calendar = TaiwanCalendar.GetDefaultInstance();
  980. dtfi = DateTimeFormatInfo.GetTaiwanCalendarDTFI();
  981. if (result.era != -1)
  982. {
  983. result.era = tokenValue;
  984. dtok.dtt = DTT.Era;
  985. }
  986. else
  987. {
  988. result.SetBadDateTimeFailure();
  989. LexTraceExit("0170 (TEraToken seen when result.era already set)", dps);
  990. return false;
  991. }
  992. break;
  993. case TokenType.TimeZoneToken:
  994. //
  995. // This is a timezone designator
  996. //
  997. // NOTENOTE : for now, we only support "GMT" and "Z" (for Zulu time).
  998. //
  999. if ((result.flags & ParseFlags.TimeZoneUsed) != 0)
  1000. {
  1001. // Should not have two timezone offsets.
  1002. result.SetBadDateTimeFailure();
  1003. LexTraceExit("0180 (seen GMT or Z more than 1x)", dps);
  1004. return false;
  1005. }
  1006. dtok.dtt = DTT.TimeZone;
  1007. result.flags |= ParseFlags.TimeZoneUsed;
  1008. result.timeZoneOffset = new TimeSpan(0);
  1009. result.flags |= ParseFlags.TimeZoneUtc;
  1010. break;
  1011. case TokenType.EndOfString:
  1012. dtok.dtt = DTT.End;
  1013. break;
  1014. case TokenType.DateWordToken:
  1015. case TokenType.IgnorableSymbol:
  1016. // Date words and ignorable symbols can just be skipped over
  1017. break;
  1018. case TokenType.Am:
  1019. case TokenType.Pm:
  1020. if (raw.timeMark == TM.NotSet)
  1021. {
  1022. raw.timeMark = (TM)tokenValue;
  1023. }
  1024. else
  1025. {
  1026. result.SetBadDateTimeFailure();
  1027. LexTraceExit("0190 (AM/PM timeMark already set)", dps);
  1028. return false;
  1029. }
  1030. break;
  1031. case TokenType.UnknownToken:
  1032. if (char.IsLetter(str.m_current))
  1033. {
  1034. result.SetFailure(ParseFailureKind.FormatWithOriginalDateTimeAndParameter, nameof(SR.Format_UnknownDateTimeWord), str.Index);
  1035. LexTraceExit("0200", dps);
  1036. return (false);
  1037. }
  1038. if ((str.m_current == '-' || str.m_current == '+') && ((result.flags & ParseFlags.TimeZoneUsed) == 0))
  1039. {
  1040. int originalIndex = str.Index;
  1041. if (ParseTimeZone(ref str, ref result.timeZoneOffset))
  1042. {
  1043. result.flags |= ParseFlags.TimeZoneUsed;
  1044. LexTraceExit("0220 (success)", dps);
  1045. return true;
  1046. }
  1047. else
  1048. {
  1049. // Time zone parse attempt failed. Fall through to punctuation handling.
  1050. str.Index = originalIndex;
  1051. }
  1052. }
  1053. // Visual Basic implements string to date conversions on top of DateTime.Parse:
  1054. // CDate("#10/10/95#")
  1055. //
  1056. if (VerifyValidPunctuation(ref str))
  1057. {
  1058. LexTraceExit("0230 (success)", dps);
  1059. return true;
  1060. }
  1061. result.SetBadDateTimeFailure();
  1062. LexTraceExit("0240", dps);
  1063. return false;
  1064. }
  1065. LexTraceExit("0250 (success)", dps);
  1066. return true;
  1067. }
  1068. private static bool VerifyValidPunctuation(ref __DTString str)
  1069. {
  1070. // Compatability Behavior. Allow trailing nulls and surrounding hashes
  1071. char ch = str.Value[str.Index];
  1072. if (ch == '#')
  1073. {
  1074. bool foundStart = false;
  1075. bool foundEnd = false;
  1076. for (int i = 0; i < str.Length; i++)
  1077. {
  1078. ch = str.Value[i];
  1079. if (ch == '#')
  1080. {
  1081. if (foundStart)
  1082. {
  1083. if (foundEnd)
  1084. {
  1085. // Having more than two hashes is invalid
  1086. return false;
  1087. }
  1088. else
  1089. {
  1090. foundEnd = true;
  1091. }
  1092. }
  1093. else
  1094. {
  1095. foundStart = true;
  1096. }
  1097. }
  1098. else if (ch == '\0')
  1099. {
  1100. // Allow nulls only at the end
  1101. if (!foundEnd)
  1102. {
  1103. return false;
  1104. }
  1105. }
  1106. else if ((!char.IsWhiteSpace(ch)))
  1107. {
  1108. // Anything other than whitespace outside hashes is invalid
  1109. if (!foundStart || foundEnd)
  1110. {
  1111. return false;
  1112. }
  1113. }
  1114. }
  1115. if (!foundEnd)
  1116. {
  1117. // The has was un-paired
  1118. return false;
  1119. }
  1120. // Valid Hash usage: eat the hash and continue.
  1121. str.GetNext();
  1122. return true;
  1123. }
  1124. else if (ch == '\0')
  1125. {
  1126. for (int i = str.Index; i < str.Length; i++)
  1127. {
  1128. if (str.Value[i] != '\0')
  1129. {
  1130. // Nulls are only valid if they are the only trailing character
  1131. return false;
  1132. }
  1133. }
  1134. // Move to the end of the string
  1135. str.Index = str.Length;
  1136. return true;
  1137. }
  1138. return false;
  1139. }
  1140. private const int ORDER_YMD = 0; // The order of date is Year/Month/Day.
  1141. private const int ORDER_MDY = 1; // The order of date is Month/Day/Year.
  1142. private const int ORDER_DMY = 2; // The order of date is Day/Month/Year.
  1143. private const int ORDER_YDM = 3; // The order of date is Year/Day/Month
  1144. private const int ORDER_YM = 4; // Year/Month order.
  1145. private const int ORDER_MY = 5; // Month/Year order.
  1146. private const int ORDER_MD = 6; // Month/Day order.
  1147. private const int ORDER_DM = 7; // Day/Month order.
  1148. //
  1149. // Decide the year/month/day order from the datePattern.
  1150. //
  1151. // Return 0 for YMD, 1 for MDY, 2 for DMY, otherwise -1.
  1152. //
  1153. private static bool GetYearMonthDayOrder(string datePattern, DateTimeFormatInfo dtfi, out int order)
  1154. {
  1155. int yearOrder = -1;
  1156. int monthOrder = -1;
  1157. int dayOrder = -1;
  1158. int orderCount = 0;
  1159. bool inQuote = false;
  1160. for (int i = 0; i < datePattern.Length && orderCount < 3; i++)
  1161. {
  1162. char ch = datePattern[i];
  1163. if (ch == '\\' || ch == '%')
  1164. {
  1165. i++;
  1166. continue; // Skip next character that is escaped by this backslash
  1167. }
  1168. if (ch == '\'' || ch == '"')
  1169. {
  1170. inQuote = !inQuote;
  1171. }
  1172. if (!inQuote)
  1173. {
  1174. if (ch == 'y')
  1175. {
  1176. yearOrder = orderCount++;
  1177. //
  1178. // Skip all year pattern charaters.
  1179. //
  1180. for (; i + 1 < datePattern.Length && datePattern[i + 1] == 'y'; i++)
  1181. {
  1182. // Do nothing here.
  1183. }
  1184. }
  1185. else if (ch == 'M')
  1186. {
  1187. monthOrder = orderCount++;
  1188. //
  1189. // Skip all month pattern characters.
  1190. //
  1191. for (; i + 1 < datePattern.Length && datePattern[i + 1] == 'M'; i++)
  1192. {
  1193. // Do nothing here.
  1194. }
  1195. }
  1196. else if (ch == 'd')
  1197. {
  1198. int patternCount = 1;
  1199. //
  1200. // Skip all day pattern characters.
  1201. //
  1202. for (; i + 1 < datePattern.Length && datePattern[i + 1] == 'd'; i++)
  1203. {
  1204. patternCount++;
  1205. }
  1206. //
  1207. // Make sure this is not "ddd" or "dddd", which means day of week.
  1208. //
  1209. if (patternCount <= 2)
  1210. {
  1211. dayOrder = orderCount++;
  1212. }
  1213. }
  1214. }
  1215. }
  1216. if (yearOrder == 0 && monthOrder == 1 && dayOrder == 2)
  1217. {
  1218. order = ORDER_YMD;
  1219. return true;
  1220. }
  1221. if (monthOrder == 0 && dayOrder == 1 && yearOrder == 2)
  1222. {
  1223. order = ORDER_MDY;
  1224. return true;
  1225. }
  1226. if (dayOrder == 0 && monthOrder == 1 && yearOrder == 2)
  1227. {
  1228. order = ORDER_DMY;
  1229. return true;
  1230. }
  1231. if (yearOrder == 0 && dayOrder == 1 && monthOrder == 2)
  1232. {
  1233. order = ORDER_YDM;
  1234. return true;
  1235. }
  1236. order = -1;
  1237. return false;
  1238. }
  1239. //
  1240. // Decide the year/month order from the pattern.
  1241. //
  1242. // Return 0 for YM, 1 for MY, otherwise -1.
  1243. //
  1244. private static bool GetYearMonthOrder(string pattern, DateTimeFormatInfo dtfi, out int order)
  1245. {
  1246. int yearOrder = -1;
  1247. int monthOrder = -1;
  1248. int orderCount = 0;
  1249. bool inQuote = false;
  1250. for (int i = 0; i < pattern.Length && orderCount < 2; i++)
  1251. {
  1252. char ch = pattern[i];
  1253. if (ch == '\\' || ch == '%')
  1254. {
  1255. i++;
  1256. continue; // Skip next character that is escaped by this backslash
  1257. }
  1258. if (ch == '\'' || ch == '"')
  1259. {
  1260. inQuote = !inQuote;
  1261. }
  1262. if (!inQuote)
  1263. {
  1264. if (ch == 'y')
  1265. {
  1266. yearOrder = orderCount++;
  1267. //
  1268. // Skip all year pattern charaters.
  1269. //
  1270. for (; i + 1 < pattern.Length && pattern[i + 1] == 'y'; i++)
  1271. {
  1272. }
  1273. }
  1274. else if (ch == 'M')
  1275. {
  1276. monthOrder = orderCount++;
  1277. //
  1278. // Skip all month pattern characters.
  1279. //
  1280. for (; i + 1 < pattern.Length && pattern[i + 1] == 'M'; i++)
  1281. {
  1282. }
  1283. }
  1284. }
  1285. }
  1286. if (yearOrder == 0 && monthOrder == 1)
  1287. {
  1288. order = ORDER_YM;
  1289. return true;
  1290. }
  1291. if (monthOrder == 0 && yearOrder == 1)
  1292. {
  1293. order = ORDER_MY;
  1294. return true;
  1295. }
  1296. order = -1;
  1297. return false;
  1298. }
  1299. //
  1300. // Decide the month/day order from the pattern.
  1301. //
  1302. // Return 0 for MD, 1 for DM, otherwise -1.
  1303. //
  1304. private static bool GetMonthDayOrder(string pattern, DateTimeFormatInfo dtfi, out int order)
  1305. {
  1306. int monthOrder = -1;
  1307. int dayOrder = -1;
  1308. int orderCount = 0;
  1309. bool inQuote = false;
  1310. for (int i = 0; i < pattern.Length && orderCount < 2; i++)
  1311. {
  1312. char ch = pattern[i];
  1313. if (ch == '\\' || ch == '%')
  1314. {
  1315. i++;
  1316. continue; // Skip next character that is escaped by this backslash
  1317. }
  1318. if (ch == '\'' || ch == '"')
  1319. {
  1320. inQuote = !inQuote;
  1321. }
  1322. if (!inQuote)
  1323. {
  1324. if (ch == 'd')
  1325. {
  1326. int patternCount = 1;
  1327. //
  1328. // Skip all day pattern charaters.
  1329. //
  1330. for (; i + 1 < pattern.Length && pattern[i + 1] == 'd'; i++)
  1331. {
  1332. patternCount++;
  1333. }
  1334. //
  1335. // Make sure this is not "ddd" or "dddd", which means day of week.
  1336. //
  1337. if (patternCount <= 2)
  1338. {
  1339. dayOrder = orderCount++;
  1340. }
  1341. }
  1342. else if (ch == 'M')
  1343. {
  1344. monthOrder = orderCount++;
  1345. //
  1346. // Skip all month pattern characters.
  1347. //
  1348. for (; i + 1 < pattern.Length && pattern[i + 1] == 'M'; i++)
  1349. {
  1350. }
  1351. }
  1352. }
  1353. }
  1354. if (monthOrder == 0 && dayOrder == 1)
  1355. {
  1356. order = ORDER_MD;
  1357. return true;
  1358. }
  1359. if (dayOrder == 0 && monthOrder == 1)
  1360. {
  1361. order = ORDER_DM;
  1362. return true;
  1363. }
  1364. order = -1;
  1365. return false;
  1366. }
  1367. //
  1368. // Adjust the two-digit year if necessary.
  1369. //
  1370. private static bool TryAdjustYear(ref DateTimeResult result, int year, out int adjustedYear)
  1371. {
  1372. if (year < 100)
  1373. {
  1374. try
  1375. {
  1376. // the Calendar classes need some real work. Many of the calendars that throw
  1377. // don't implement a fast/non-allocating (and non-throwing) IsValid{Year|Day|Month} method.
  1378. // we are making a targeted try/catch fix in the in-place release but will revisit this code
  1379. // in the next side-by-side release.
  1380. year = result.calendar.ToFourDigitYear(year);
  1381. }
  1382. catch (ArgumentOutOfRangeException)
  1383. {
  1384. adjustedYear = -1;
  1385. return false;
  1386. }
  1387. }
  1388. adjustedYear = year;
  1389. return true;
  1390. }
  1391. private static bool SetDateYMD(ref DateTimeResult result, int year, int month, int day)
  1392. {
  1393. // Note, longer term these checks should be done at the end of the parse. This current
  1394. // way of checking creates order dependence with parsing the era name.
  1395. if (result.calendar.IsValidDay(year, month, day, result.era))
  1396. {
  1397. result.SetDate(year, month, day); // YMD
  1398. return (true);
  1399. }
  1400. return (false);
  1401. }
  1402. private static bool SetDateMDY(ref DateTimeResult result, int month, int day, int year)
  1403. {
  1404. return (SetDateYMD(ref result, year, month, day));
  1405. }
  1406. private static bool SetDateDMY(ref DateTimeResult result, int day, int month, int year)
  1407. {
  1408. return (SetDateYMD(ref result, year, month, day));
  1409. }
  1410. private static bool SetDateYDM(ref DateTimeResult result, int year, int day, int month)
  1411. {
  1412. return (SetDateYMD(ref result, year, month, day));
  1413. }
  1414. private static void GetDefaultYear(ref DateTimeResult result, ref DateTimeStyles styles)
  1415. {
  1416. result.Year = result.calendar.GetYear(GetDateTimeNow(ref result, ref styles));
  1417. result.flags |= ParseFlags.YearDefault;
  1418. }
  1419. // Processing teriminal case: DS.DX_NN
  1420. private static bool GetDayOfNN(ref DateTimeResult result, ref DateTimeStyles styles, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi)
  1421. {
  1422. if ((result.flags & ParseFlags.HaveDate) != 0)
  1423. {
  1424. // Multiple dates in the input string
  1425. result.SetBadDateTimeFailure();
  1426. return false;
  1427. }
  1428. int n1 = raw.GetNumber(0);
  1429. int n2 = raw.GetNumber(1);
  1430. GetDefaultYear(ref result, ref styles);
  1431. int order;
  1432. if (!GetMonthDayOrder(dtfi.MonthDayPattern, dtfi, out order))
  1433. {
  1434. result.SetFailure(ParseFailureKind.FormatWithParameter, nameof(SR.Format_BadDatePattern), dtfi.MonthDayPattern);
  1435. return false;
  1436. }
  1437. if (order == ORDER_MD)
  1438. {
  1439. if (SetDateYMD(ref result, result.Year, n1, n2)) // MD
  1440. {
  1441. result.flags |= ParseFlags.HaveDate;
  1442. return true;
  1443. }
  1444. }
  1445. else
  1446. {
  1447. // ORDER_DM
  1448. if (SetDateYMD(ref result, result.Year, n2, n1)) // DM
  1449. {
  1450. result.flags |= ParseFlags.HaveDate;
  1451. return true;
  1452. }
  1453. }
  1454. result.SetBadDateTimeFailure();
  1455. return false;
  1456. }
  1457. // Processing teriminal case: DS.DX_NNN
  1458. private static bool GetDayOfNNN(ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi)
  1459. {
  1460. if ((result.flags & ParseFlags.HaveDate) != 0)
  1461. {
  1462. // Multiple dates in the input string
  1463. result.SetBadDateTimeFailure();
  1464. return false;
  1465. }
  1466. int n1 = raw.GetNumber(0);
  1467. int n2 = raw.GetNumber(1); ;
  1468. int n3 = raw.GetNumber(2);
  1469. int order;
  1470. if (!GetYearMonthDayOrder(dtfi.ShortDatePattern, dtfi, out order))
  1471. {
  1472. result.SetFailure(ParseFailureKind.FormatWithParameter, nameof(SR.Format_BadDatePattern), dtfi.ShortDatePattern);
  1473. return false;
  1474. }
  1475. int year;
  1476. if (order == ORDER_YMD)
  1477. {
  1478. if (TryAdjustYear(ref result, n1, out year) && SetDateYMD(ref result, year, n2, n3)) // YMD
  1479. {
  1480. result.flags |= ParseFlags.HaveDate;
  1481. return true;
  1482. }
  1483. }
  1484. else if (order == ORDER_MDY)
  1485. {
  1486. if (TryAdjustYear(ref result, n3, out year) && SetDateMDY(ref result, n1, n2, year)) // MDY
  1487. {
  1488. result.flags |= ParseFlags.HaveDate;
  1489. return true;
  1490. }
  1491. }
  1492. else if (order == ORDER_DMY)
  1493. {
  1494. if (TryAdjustYear(ref result, n3, out year) && SetDateDMY(ref result, n1, n2, year)) // DMY
  1495. {
  1496. result.flags |= ParseFlags.HaveDate;
  1497. return true;
  1498. }
  1499. }
  1500. else if (order == ORDER_YDM)
  1501. {
  1502. if (TryAdjustYear(ref result, n1, out year) && SetDateYDM(ref result, year, n2, n3)) // YDM
  1503. {
  1504. result.flags |= ParseFlags.HaveDate;
  1505. return true;
  1506. }
  1507. }
  1508. result.SetBadDateTimeFailure();
  1509. return false;
  1510. }
  1511. private static bool GetDayOfMN(ref DateTimeResult result, ref DateTimeStyles styles, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi)
  1512. {
  1513. if ((result.flags & ParseFlags.HaveDate) != 0)
  1514. {
  1515. // Multiple dates in the input string
  1516. result.SetBadDateTimeFailure();
  1517. return false;
  1518. }
  1519. // The interpretation is based on the MonthDayPattern and YearMonthPattern
  1520. //
  1521. // MonthDayPattern YearMonthPattern Interpretation
  1522. // --------------- ---------------- ---------------
  1523. // MMMM dd MMMM yyyy Day
  1524. // MMMM dd yyyy MMMM Day
  1525. // dd MMMM MMMM yyyy Year
  1526. // dd MMMM yyyy MMMM Day
  1527. //
  1528. // In the first and last cases, it could be either or neither, but a day is a better default interpretation
  1529. // than a 2 digit year.
  1530. int monthDayOrder;
  1531. if (!GetMonthDayOrder(dtfi.MonthDayPattern, dtfi, out monthDayOrder))
  1532. {
  1533. result.SetFailure(ParseFailureKind.FormatWithParameter, nameof(SR.Format_BadDatePattern), dtfi.MonthDayPattern);
  1534. return false;
  1535. }
  1536. if (monthDayOrder == ORDER_DM)
  1537. {
  1538. int yearMonthOrder;
  1539. if (!GetYearMonthOrder(dtfi.YearMonthPattern, dtfi, out yearMonthOrder))
  1540. {
  1541. result.SetFailure(ParseFailureKind.FormatWithParameter, nameof(SR.Format_BadDatePattern), dtfi.YearMonthPattern);
  1542. return false;
  1543. }
  1544. if (yearMonthOrder == ORDER_MY)
  1545. {
  1546. int year;
  1547. if (!TryAdjustYear(ref result, raw.GetNumber(0), out year) || !SetDateYMD(ref result, year, raw.month, 1))
  1548. {
  1549. result.SetBadDateTimeFailure();
  1550. return false;
  1551. }
  1552. return true;
  1553. }
  1554. }
  1555. GetDefaultYear(ref result, ref styles);
  1556. if (!SetDateYMD(ref result, result.Year, raw.month, raw.GetNumber(0)))
  1557. {
  1558. result.SetBadDateTimeFailure();
  1559. return false;
  1560. }
  1561. return true;
  1562. }
  1563. ////////////////////////////////////////////////////////////////////////
  1564. // Actions:
  1565. // Deal with the terminal state for Hebrew Month/Day pattern
  1566. //
  1567. ////////////////////////////////////////////////////////////////////////
  1568. private static bool GetHebrewDayOfNM(ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi)
  1569. {
  1570. int monthDayOrder;
  1571. if (!GetMonthDayOrder(dtfi.MonthDayPattern, dtfi, out monthDayOrder))
  1572. {
  1573. result.SetFailure(ParseFailureKind.FormatWithParameter, nameof(SR.Format_BadDatePattern), dtfi.MonthDayPattern);
  1574. return false;
  1575. }
  1576. result.Month = raw.month;
  1577. if (monthDayOrder == ORDER_DM || monthDayOrder == ORDER_MD)
  1578. {
  1579. if (result.calendar.IsValidDay(result.Year, result.Month, raw.GetNumber(0), result.era))
  1580. {
  1581. result.Day = raw.GetNumber(0);
  1582. return true;
  1583. }
  1584. }
  1585. result.SetBadDateTimeFailure();
  1586. return false;
  1587. }
  1588. private static bool GetDayOfNM(ref DateTimeResult result, ref DateTimeStyles styles, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi)
  1589. {
  1590. if ((result.flags & ParseFlags.HaveDate) != 0)
  1591. {
  1592. // Multiple dates in the input string
  1593. result.SetBadDateTimeFailure();
  1594. return false;
  1595. }
  1596. // The interpretation is based on the MonthDayPattern and YearMonthPattern
  1597. //
  1598. // MonthDayPattern YearMonthPattern Interpretation
  1599. // --------------- ---------------- ---------------
  1600. // MMMM dd MMMM yyyy Day
  1601. // MMMM dd yyyy MMMM Year
  1602. // dd MMMM MMMM yyyy Day
  1603. // dd MMMM yyyy MMMM Day
  1604. //
  1605. // In the first and last cases, it could be either or neither, but a day is a better default interpretation
  1606. // than a 2 digit year.
  1607. int monthDayOrder;
  1608. if (!GetMonthDayOrder(dtfi.MonthDayPattern, dtfi, out monthDayOrder))
  1609. {
  1610. result.SetFailure(ParseFailureKind.FormatWithParameter, nameof(SR.Format_BadDatePattern), dtfi.MonthDayPattern);
  1611. return false;
  1612. }
  1613. if (monthDayOrder == ORDER_MD)
  1614. {
  1615. int yearMonthOrder;
  1616. if (!GetYearMonthOrder(dtfi.YearMonthPattern, dtfi, out yearMonthOrder))
  1617. {
  1618. result.SetFailure(ParseFailureKind.FormatWithParameter, nameof(SR.Format_BadDatePattern), dtfi.YearMonthPattern);
  1619. return false;
  1620. }
  1621. if (yearMonthOrder == ORDER_YM)
  1622. {
  1623. int year;
  1624. if (!TryAdjustYear(ref result, raw.GetNumber(0), out year) || !SetDateYMD(ref result, year, raw.month, 1))
  1625. {
  1626. result.SetBadDateTimeFailure();
  1627. return false;
  1628. }
  1629. return true;
  1630. }
  1631. }
  1632. GetDefaultYear(ref result, ref styles);
  1633. if (!SetDateYMD(ref result, result.Year, raw.month, raw.GetNumber(0)))
  1634. {
  1635. result.SetBadDateTimeFailure();
  1636. return false;
  1637. }
  1638. return true;
  1639. }
  1640. private static bool GetDayOfMNN(ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi)
  1641. {
  1642. if ((result.flags & ParseFlags.HaveDate) != 0)
  1643. {
  1644. // Multiple dates in the input string
  1645. result.SetBadDateTimeFailure();
  1646. return false;
  1647. }
  1648. int n1 = raw.GetNumber(0);
  1649. int n2 = raw.GetNumber(1);
  1650. int order;
  1651. if (!GetYearMonthDayOrder(dtfi.ShortDatePattern, dtfi, out order))
  1652. {
  1653. result.SetFailure(ParseFailureKind.FormatWithParameter, nameof(SR.Format_BadDatePattern), dtfi.ShortDatePattern);
  1654. return false;
  1655. }
  1656. int year;
  1657. if (order == ORDER_MDY)
  1658. {
  1659. if (TryAdjustYear(ref result, n2, out year) && result.calendar.IsValidDay(year, raw.month, n1, result.era))
  1660. {
  1661. result.SetDate(year, raw.month, n1); // MDY
  1662. result.flags |= ParseFlags.HaveDate;
  1663. return true;
  1664. }
  1665. else if (TryAdjustYear(ref result, n1, out year) && result.calendar.IsValidDay(year, raw.month, n2, result.era))
  1666. {
  1667. result.SetDate(year, raw.month, n2); // YMD
  1668. result.flags |= ParseFlags.HaveDate;
  1669. return true;
  1670. }
  1671. }
  1672. else if (order == ORDER_YMD)
  1673. {
  1674. if (TryAdjustYear(ref result, n1, out year) && result.calendar.IsValidDay(year, raw.month, n2, result.era))
  1675. {
  1676. result.SetDate(year, raw.month, n2); // YMD
  1677. result.flags |= ParseFlags.HaveDate;
  1678. return true;
  1679. }
  1680. else if (TryAdjustYear(ref result, n2, out year) && result.calendar.IsValidDay(year, raw.month, n1, result.era))
  1681. {
  1682. result.SetDate(year, raw.month, n1); // DMY
  1683. result.flags |= ParseFlags.HaveDate;
  1684. return true;
  1685. }
  1686. }
  1687. else if (order == ORDER_DMY)
  1688. {
  1689. if (TryAdjustYear(ref result, n2, out year) && result.calendar.IsValidDay(year, raw.month, n1, result.era))
  1690. {
  1691. result.SetDate(year, raw.month, n1); // DMY
  1692. result.flags |= ParseFlags.HaveDate;
  1693. return true;
  1694. }
  1695. else if (TryAdjustYear(ref result, n1, out year) && result.calendar.IsValidDay(year, raw.month, n2, result.era))
  1696. {
  1697. result.SetDate(year, raw.month, n2); // YMD
  1698. result.flags |= ParseFlags.HaveDate;
  1699. return true;
  1700. }
  1701. }
  1702. result.SetBadDateTimeFailure();
  1703. return false;
  1704. }
  1705. private static bool GetDayOfYNN(ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi)
  1706. {
  1707. if ((result.flags & ParseFlags.HaveDate) != 0)
  1708. {
  1709. // Multiple dates in the input string
  1710. result.SetBadDateTimeFailure();
  1711. return false;
  1712. }
  1713. int n1 = raw.GetNumber(0);
  1714. int n2 = raw.GetNumber(1);
  1715. string pattern = dtfi.ShortDatePattern;
  1716. // For compatibility, don't throw if we can't determine the order, but default to YMD instead
  1717. int order;
  1718. if (GetYearMonthDayOrder(pattern, dtfi, out order) && order == ORDER_YDM)
  1719. {
  1720. if (SetDateYMD(ref result, raw.year, n2, n1))
  1721. {
  1722. result.flags |= ParseFlags.HaveDate;
  1723. return true; // Year + DM
  1724. }
  1725. }
  1726. else
  1727. {
  1728. if (SetDateYMD(ref result, raw.year, n1, n2))
  1729. {
  1730. result.flags |= ParseFlags.HaveDate;
  1731. return true; // Year + MD
  1732. }
  1733. }
  1734. result.SetBadDateTimeFailure();
  1735. return false;
  1736. }
  1737. private static bool GetDayOfNNY(ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi)
  1738. {
  1739. if ((result.flags & ParseFlags.HaveDate) != 0)
  1740. {
  1741. // Multiple dates in the input string
  1742. result.SetBadDateTimeFailure();
  1743. return false;
  1744. }
  1745. int n1 = raw.GetNumber(0);
  1746. int n2 = raw.GetNumber(1);
  1747. int order;
  1748. if (!GetYearMonthDayOrder(dtfi.ShortDatePattern, dtfi, out order))
  1749. {
  1750. result.SetFailure(ParseFailureKind.FormatWithParameter, nameof(SR.Format_BadDatePattern), dtfi.ShortDatePattern);
  1751. return false;
  1752. }
  1753. if (order == ORDER_MDY || order == ORDER_YMD)
  1754. {
  1755. if (SetDateYMD(ref result, raw.year, n1, n2))
  1756. {
  1757. result.flags |= ParseFlags.HaveDate;
  1758. return true; // MD + Year
  1759. }
  1760. }
  1761. else
  1762. {
  1763. if (SetDateYMD(ref result, raw.year, n2, n1))
  1764. {
  1765. result.flags |= ParseFlags.HaveDate;
  1766. return true; // DM + Year
  1767. }
  1768. }
  1769. result.SetBadDateTimeFailure();
  1770. return false;
  1771. }
  1772. private static bool GetDayOfYMN(ref DateTimeResult result, ref DateTimeRawInfo raw)
  1773. {
  1774. if ((result.flags & ParseFlags.HaveDate) != 0)
  1775. {
  1776. // Multiple dates in the input string
  1777. result.SetBadDateTimeFailure();
  1778. return false;
  1779. }
  1780. if (SetDateYMD(ref result, raw.year, raw.month, raw.GetNumber(0)))
  1781. {
  1782. result.flags |= ParseFlags.HaveDate;
  1783. return true;
  1784. }
  1785. result.SetBadDateTimeFailure();
  1786. return false;
  1787. }
  1788. private static bool GetDayOfYN(ref DateTimeResult result, ref DateTimeRawInfo raw)
  1789. {
  1790. if ((result.flags & ParseFlags.HaveDate) != 0)
  1791. {
  1792. // Multiple dates in the input string
  1793. result.SetBadDateTimeFailure();
  1794. return false;
  1795. }
  1796. if (SetDateYMD(ref result, raw.year, raw.GetNumber(0), 1))
  1797. {
  1798. result.flags |= ParseFlags.HaveDate;
  1799. return true;
  1800. }
  1801. result.SetBadDateTimeFailure();
  1802. return false;
  1803. }
  1804. private static bool GetDayOfYM(ref DateTimeResult result, ref DateTimeRawInfo raw)
  1805. {
  1806. if ((result.flags & ParseFlags.HaveDate) != 0)
  1807. {
  1808. // Multiple dates in the input string
  1809. result.SetBadDateTimeFailure();
  1810. return false;
  1811. }
  1812. if (SetDateYMD(ref result, raw.year, raw.month, 1))
  1813. {
  1814. result.flags |= ParseFlags.HaveDate;
  1815. return true;
  1816. }
  1817. result.SetBadDateTimeFailure();
  1818. return false;
  1819. }
  1820. private static void AdjustTimeMark(DateTimeFormatInfo dtfi, ref DateTimeRawInfo raw)
  1821. {
  1822. // Specail case for culture which uses AM as empty string.
  1823. // E.g. af-ZA (0x0436)
  1824. // S1159 \x0000
  1825. // S2359 nm
  1826. // In this case, if we are parsing a string like "2005/09/14 12:23", we will assume this is in AM.
  1827. if (raw.timeMark == TM.NotSet)
  1828. {
  1829. if (dtfi.AMDesignator != null && dtfi.PMDesignator != null)
  1830. {
  1831. if (dtfi.AMDesignator.Length == 0 && dtfi.PMDesignator.Length != 0)
  1832. {
  1833. raw.timeMark = TM.AM;
  1834. }
  1835. if (dtfi.PMDesignator.Length == 0 && dtfi.AMDesignator.Length != 0)
  1836. {
  1837. raw.timeMark = TM.PM;
  1838. }
  1839. }
  1840. }
  1841. }
  1842. //
  1843. // Adjust hour according to the time mark.
  1844. //
  1845. private static bool AdjustHour(ref int hour, TM timeMark)
  1846. {
  1847. if (timeMark != TM.NotSet)
  1848. {
  1849. if (timeMark == TM.AM)
  1850. {
  1851. if (hour < 0 || hour > 12)
  1852. {
  1853. return false;
  1854. }
  1855. hour = (hour == 12) ? 0 : hour;
  1856. }
  1857. else
  1858. {
  1859. if (hour < 0 || hour > 23)
  1860. {
  1861. return false;
  1862. }
  1863. if (hour < 12)
  1864. {
  1865. hour += 12;
  1866. }
  1867. }
  1868. }
  1869. return true;
  1870. }
  1871. private static bool GetTimeOfN(ref DateTimeResult result, ref DateTimeRawInfo raw)
  1872. {
  1873. if ((result.flags & ParseFlags.HaveTime) != 0)
  1874. {
  1875. // Multiple times in the input string
  1876. result.SetBadDateTimeFailure();
  1877. return false;
  1878. }
  1879. //
  1880. // In this case, we need a time mark. Check if so.
  1881. //
  1882. if (raw.timeMark == TM.NotSet)
  1883. {
  1884. result.SetBadDateTimeFailure();
  1885. return false;
  1886. }
  1887. result.Hour = raw.GetNumber(0);
  1888. result.flags |= ParseFlags.HaveTime;
  1889. return true;
  1890. }
  1891. private static bool GetTimeOfNN(ref DateTimeResult result, ref DateTimeRawInfo raw)
  1892. {
  1893. Debug.Assert(raw.numCount >= 2, "raw.numCount >= 2");
  1894. if ((result.flags & ParseFlags.HaveTime) != 0)
  1895. {
  1896. // Multiple times in the input string
  1897. result.SetBadDateTimeFailure();
  1898. return false;
  1899. }
  1900. result.Hour = raw.GetNumber(0);
  1901. result.Minute = raw.GetNumber(1);
  1902. result.flags |= ParseFlags.HaveTime;
  1903. return true;
  1904. }
  1905. private static bool GetTimeOfNNN(ref DateTimeResult result, ref DateTimeRawInfo raw)
  1906. {
  1907. if ((result.flags & ParseFlags.HaveTime) != 0)
  1908. {
  1909. // Multiple times in the input string
  1910. result.SetBadDateTimeFailure();
  1911. return false;
  1912. }
  1913. Debug.Assert(raw.numCount >= 3, "raw.numCount >= 3");
  1914. result.Hour = raw.GetNumber(0);
  1915. result.Minute = raw.GetNumber(1);
  1916. result.Second = raw.GetNumber(2);
  1917. result.flags |= ParseFlags.HaveTime;
  1918. return true;
  1919. }
  1920. //
  1921. // Processing terminal state: A Date suffix followed by one number.
  1922. //
  1923. private static bool GetDateOfDSN(ref DateTimeResult result, ref DateTimeRawInfo raw)
  1924. {
  1925. if (raw.numCount != 1 || result.Day != -1)
  1926. {
  1927. result.SetBadDateTimeFailure();
  1928. return false;
  1929. }
  1930. result.Day = raw.GetNumber(0);
  1931. return true;
  1932. }
  1933. private static bool GetDateOfNDS(ref DateTimeResult result, ref DateTimeRawInfo raw)
  1934. {
  1935. if (result.Month == -1)
  1936. {
  1937. //Should have a month suffix
  1938. result.SetBadDateTimeFailure();
  1939. return false;
  1940. }
  1941. if (result.Year != -1)
  1942. {
  1943. // Already has a year suffix
  1944. result.SetBadDateTimeFailure();
  1945. return false;
  1946. }
  1947. if (!TryAdjustYear(ref result, raw.GetNumber(0), out result.Year))
  1948. {
  1949. // the year value is out of range
  1950. result.SetBadDateTimeFailure();
  1951. return false;
  1952. }
  1953. result.Day = 1;
  1954. return true;
  1955. }
  1956. private static bool GetDateOfNNDS(ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi)
  1957. {
  1958. // For partial CJK Dates, the only valid formats are with a specified year, followed by two numbers, which
  1959. // will be the Month and Day, and with a specified Month, when the numbers are either the year and day or
  1960. // day and year, depending on the short date pattern.
  1961. if ((result.flags & ParseFlags.HaveYear) != 0)
  1962. {
  1963. if (((result.flags & ParseFlags.HaveMonth) == 0) && ((result.flags & ParseFlags.HaveDay) == 0))
  1964. {
  1965. if (TryAdjustYear(ref result, raw.year, out result.Year) && SetDateYMD(ref result, result.Year, raw.GetNumber(0), raw.GetNumber(1)))
  1966. {
  1967. return true;
  1968. }
  1969. }
  1970. }
  1971. else if ((result.flags & ParseFlags.HaveMonth) != 0)
  1972. {
  1973. if (((result.flags & ParseFlags.HaveYear) == 0) && ((result.flags & ParseFlags.HaveDay) == 0))
  1974. {
  1975. int order;
  1976. if (!GetYearMonthDayOrder(dtfi.ShortDatePattern, dtfi, out order))
  1977. {
  1978. result.SetFailure(ParseFailureKind.FormatWithParameter, nameof(SR.Format_BadDatePattern), dtfi.ShortDatePattern);
  1979. return false;
  1980. }
  1981. int year;
  1982. if (order == ORDER_YMD)
  1983. {
  1984. if (TryAdjustYear(ref result, raw.GetNumber(0), out year) && SetDateYMD(ref result, year, result.Month, raw.GetNumber(1)))
  1985. {
  1986. return true;
  1987. }
  1988. }
  1989. else
  1990. {
  1991. if (TryAdjustYear(ref result, raw.GetNumber(1), out year) && SetDateYMD(ref result, year, result.Month, raw.GetNumber(0)))
  1992. {
  1993. return true;
  1994. }
  1995. }
  1996. }
  1997. }
  1998. result.SetBadDateTimeFailure();
  1999. return false;
  2000. }
  2001. //
  2002. // A date suffix is found, use this method to put the number into the result.
  2003. //
  2004. private static bool ProcessDateTimeSuffix(ref DateTimeResult result, ref DateTimeRawInfo raw, ref DateTimeToken dtok)
  2005. {
  2006. switch (dtok.suffix)
  2007. {
  2008. case TokenType.SEP_YearSuff:
  2009. if ((result.flags & ParseFlags.HaveYear) != 0)
  2010. {
  2011. return false;
  2012. }
  2013. result.flags |= ParseFlags.HaveYear;
  2014. result.Year = raw.year = dtok.num;
  2015. break;
  2016. case TokenType.SEP_MonthSuff:
  2017. if ((result.flags & ParseFlags.HaveMonth) != 0)
  2018. {
  2019. return false;
  2020. }
  2021. result.flags |= ParseFlags.HaveMonth;
  2022. result.Month = raw.month = dtok.num;
  2023. break;
  2024. case TokenType.SEP_DaySuff:
  2025. if ((result.flags & ParseFlags.HaveDay) != 0)
  2026. {
  2027. return false;
  2028. }
  2029. result.flags |= ParseFlags.HaveDay;
  2030. result.Day = dtok.num;
  2031. break;
  2032. case TokenType.SEP_HourSuff:
  2033. if ((result.flags & ParseFlags.HaveHour) != 0)
  2034. {
  2035. return false;
  2036. }
  2037. result.flags |= ParseFlags.HaveHour;
  2038. result.Hour = dtok.num;
  2039. break;
  2040. case TokenType.SEP_MinuteSuff:
  2041. if ((result.flags & ParseFlags.HaveMinute) != 0)
  2042. {
  2043. return false;
  2044. }
  2045. result.flags |= ParseFlags.HaveMinute;
  2046. result.Minute = dtok.num;
  2047. break;
  2048. case TokenType.SEP_SecondSuff:
  2049. if ((result.flags & ParseFlags.HaveSecond) != 0)
  2050. {
  2051. return false;
  2052. }
  2053. result.flags |= ParseFlags.HaveSecond;
  2054. result.Second = dtok.num;
  2055. break;
  2056. }
  2057. return true;
  2058. }
  2059. ////////////////////////////////////////////////////////////////////////
  2060. //
  2061. // Actions:
  2062. // This is used by DateTime.Parse().
  2063. // Process the terminal state for the Hebrew calendar parsing.
  2064. //
  2065. ////////////////////////////////////////////////////////////////////////
  2066. internal static bool ProcessHebrewTerminalState(DS dps, ref __DTString str, ref DateTimeResult result, ref DateTimeStyles styles, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi)
  2067. {
  2068. // The following are accepted terminal state for Hebrew date.
  2069. switch (dps)
  2070. {
  2071. case DS.DX_MNN:
  2072. // Deal with the default long/short date format when the year number is ambigous (i.e. year < 100).
  2073. raw.year = raw.GetNumber(1);
  2074. if (!dtfi.YearMonthAdjustment(ref raw.year, ref raw.month, true))
  2075. {
  2076. result.SetFailure(ParseFailureKind.FormatBadDateTimeCalendar, nameof(SR.Format_BadDateTimeCalendar));
  2077. return false;
  2078. }
  2079. if (!GetDayOfMNN(ref result, ref raw, dtfi))
  2080. {
  2081. return false;
  2082. }
  2083. break;
  2084. case DS.DX_YMN:
  2085. // Deal with the default long/short date format when the year number is NOT ambigous (i.e. year >= 100).
  2086. if (!dtfi.YearMonthAdjustment(ref raw.year, ref raw.month, true))
  2087. {
  2088. result.SetFailure(ParseFailureKind.FormatBadDateTimeCalendar, nameof(SR.Format_BadDateTimeCalendar));
  2089. return false;
  2090. }
  2091. if (!GetDayOfYMN(ref result, ref raw))
  2092. {
  2093. return false;
  2094. }
  2095. break;
  2096. case DS.DX_NNY:
  2097. // When formatting, we only format up to the hundred digit of the Hebrew year, although Hebrew year is now over 5000.
  2098. // E.g. if the year is 5763, we only format as 763. so we do the reverse when parsing.
  2099. if (raw.year < 1000)
  2100. {
  2101. raw.year += 5000;
  2102. }
  2103. if (!GetDayOfNNY(ref result, ref raw, dtfi))
  2104. {
  2105. return false;
  2106. }
  2107. if (!dtfi.YearMonthAdjustment(ref result.Year, ref raw.month, true))
  2108. {
  2109. result.SetFailure(ParseFailureKind.FormatBadDateTimeCalendar, nameof(SR.Format_BadDateTimeCalendar));
  2110. return false;
  2111. }
  2112. break;
  2113. case DS.DX_NM:
  2114. case DS.DX_MN:
  2115. // Deal with Month/Day pattern.
  2116. GetDefaultYear(ref result, ref styles);
  2117. if (!dtfi.YearMonthAdjustment(ref result.Year, ref raw.month, true))
  2118. {
  2119. result.SetFailure(ParseFailureKind.FormatBadDateTimeCalendar, nameof(SR.Format_BadDateTimeCalendar));
  2120. return false;
  2121. }
  2122. if (!GetHebrewDayOfNM(ref result, ref raw, dtfi))
  2123. {
  2124. return false;
  2125. }
  2126. break;
  2127. case DS.DX_YM:
  2128. // Deal with Year/Month pattern.
  2129. if (!dtfi.YearMonthAdjustment(ref raw.year, ref raw.month, true))
  2130. {
  2131. result.SetFailure(ParseFailureKind.FormatBadDateTimeCalendar, nameof(SR.Format_BadDateTimeCalendar));
  2132. return false;
  2133. }
  2134. if (!GetDayOfYM(ref result, ref raw))
  2135. {
  2136. return false;
  2137. }
  2138. break;
  2139. case DS.TX_N:
  2140. // Deal hour + AM/PM
  2141. if (!GetTimeOfN(ref result, ref raw))
  2142. {
  2143. return false;
  2144. }
  2145. break;
  2146. case DS.TX_NN:
  2147. if (!GetTimeOfNN(ref result, ref raw))
  2148. {
  2149. return false;
  2150. }
  2151. break;
  2152. case DS.TX_NNN:
  2153. if (!GetTimeOfNNN(ref result, ref raw))
  2154. {
  2155. return false;
  2156. }
  2157. break;
  2158. default:
  2159. result.SetBadDateTimeFailure();
  2160. return false;
  2161. }
  2162. if (dps > DS.ERROR)
  2163. {
  2164. //
  2165. // We have reached a terminal state. Reset the raw num count.
  2166. //
  2167. raw.numCount = 0;
  2168. }
  2169. return true;
  2170. }
  2171. //
  2172. // A terminal state has been reached, call the appropriate function to fill in the parsing result.
  2173. // Return true if the state is a terminal state.
  2174. //
  2175. internal static bool ProcessTerminalState(DS dps, ref __DTString str, ref DateTimeResult result, ref DateTimeStyles styles, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi)
  2176. {
  2177. bool passed = true;
  2178. switch (dps)
  2179. {
  2180. case DS.DX_NN:
  2181. passed = GetDayOfNN(ref result, ref styles, ref raw, dtfi);
  2182. break;
  2183. case DS.DX_NNN:
  2184. passed = GetDayOfNNN(ref result, ref raw, dtfi);
  2185. break;
  2186. case DS.DX_MN:
  2187. passed = GetDayOfMN(ref result, ref styles, ref raw, dtfi);
  2188. break;
  2189. case DS.DX_NM:
  2190. passed = GetDayOfNM(ref result, ref styles, ref raw, dtfi);
  2191. break;
  2192. case DS.DX_MNN:
  2193. passed = GetDayOfMNN(ref result, ref raw, dtfi);
  2194. break;
  2195. case DS.DX_DS:
  2196. // The result has got the correct value. No need to process.
  2197. passed = true;
  2198. break;
  2199. case DS.DX_YNN:
  2200. passed = GetDayOfYNN(ref result, ref raw, dtfi);
  2201. break;
  2202. case DS.DX_NNY:
  2203. passed = GetDayOfNNY(ref result, ref raw, dtfi);
  2204. break;
  2205. case DS.DX_YMN:
  2206. passed = GetDayOfYMN(ref result, ref raw);
  2207. break;
  2208. case DS.DX_YN:
  2209. passed = GetDayOfYN(ref result, ref raw);
  2210. break;
  2211. case DS.DX_YM:
  2212. passed = GetDayOfYM(ref result, ref raw);
  2213. break;
  2214. case DS.TX_N:
  2215. passed = GetTimeOfN(ref result, ref raw);
  2216. break;
  2217. case DS.TX_NN:
  2218. passed = GetTimeOfNN(ref result, ref raw);
  2219. break;
  2220. case DS.TX_NNN:
  2221. passed = GetTimeOfNNN(ref result, ref raw);
  2222. break;
  2223. case DS.TX_TS:
  2224. // The result has got the correct value. Nothing to do.
  2225. passed = true;
  2226. break;
  2227. case DS.DX_DSN:
  2228. passed = GetDateOfDSN(ref result, ref raw);
  2229. break;
  2230. case DS.DX_NDS:
  2231. passed = GetDateOfNDS(ref result, ref raw);
  2232. break;
  2233. case DS.DX_NNDS:
  2234. passed = GetDateOfNNDS(ref result, ref raw, dtfi);
  2235. break;
  2236. }
  2237. PTSTraceExit(dps, passed);
  2238. if (!passed)
  2239. {
  2240. return false;
  2241. }
  2242. if (dps > DS.ERROR)
  2243. {
  2244. //
  2245. // We have reached a terminal state. Reset the raw num count.
  2246. //
  2247. raw.numCount = 0;
  2248. }
  2249. return true;
  2250. }
  2251. internal static DateTime Parse(ReadOnlySpan<char> s, DateTimeFormatInfo dtfi, DateTimeStyles styles)
  2252. {
  2253. DateTimeResult result = new DateTimeResult(); // The buffer to store the parsing result.
  2254. result.Init(s);
  2255. if (TryParse(s, dtfi, styles, ref result))
  2256. {
  2257. return result.parsedDate;
  2258. }
  2259. else
  2260. {
  2261. throw GetDateTimeParseException(ref result);
  2262. }
  2263. }
  2264. internal static DateTime Parse(ReadOnlySpan<char> s, DateTimeFormatInfo dtfi, DateTimeStyles styles, out TimeSpan offset)
  2265. {
  2266. DateTimeResult result = new DateTimeResult(); // The buffer to store the parsing result.
  2267. result.Init(s);
  2268. result.flags |= ParseFlags.CaptureOffset;
  2269. if (TryParse(s, dtfi, styles, ref result))
  2270. {
  2271. offset = result.timeZoneOffset;
  2272. return result.parsedDate;
  2273. }
  2274. else
  2275. {
  2276. throw GetDateTimeParseException(ref result);
  2277. }
  2278. }
  2279. internal static bool TryParse(ReadOnlySpan<char> s, DateTimeFormatInfo dtfi, DateTimeStyles styles, out DateTime result)
  2280. {
  2281. result = DateTime.MinValue;
  2282. DateTimeResult resultData = new DateTimeResult(); // The buffer to store the parsing result.
  2283. resultData.Init(s);
  2284. if (TryParse(s, dtfi, styles, ref resultData))
  2285. {
  2286. result = resultData.parsedDate;
  2287. return true;
  2288. }
  2289. return false;
  2290. }
  2291. internal static bool TryParse(ReadOnlySpan<char> s, DateTimeFormatInfo dtfi, DateTimeStyles styles, out DateTime result, out TimeSpan offset)
  2292. {
  2293. result = DateTime.MinValue;
  2294. offset = TimeSpan.Zero;
  2295. DateTimeResult parseResult = new DateTimeResult(); // The buffer to store the parsing result.
  2296. parseResult.Init(s);
  2297. parseResult.flags |= ParseFlags.CaptureOffset;
  2298. if (TryParse(s, dtfi, styles, ref parseResult))
  2299. {
  2300. result = parseResult.parsedDate;
  2301. offset = parseResult.timeZoneOffset;
  2302. return true;
  2303. }
  2304. return false;
  2305. }
  2306. //
  2307. // This is the real method to do the parsing work.
  2308. //
  2309. internal static bool TryParse(ReadOnlySpan<char> s, DateTimeFormatInfo dtfi, DateTimeStyles styles, ref DateTimeResult result)
  2310. {
  2311. if (s.Length == 0)
  2312. {
  2313. result.SetFailure(ParseFailureKind.FormatWithParameter, nameof(SR.Format_BadDateTime));
  2314. return false;
  2315. }
  2316. Debug.Assert(dtfi != null, "dtfi == null");
  2317. #if _LOGGING
  2318. DTFITrace(dtfi);
  2319. #endif
  2320. DateTime time;
  2321. //
  2322. // First try the predefined format.
  2323. //
  2324. DS dps = DS.BEGIN; // Date Parsing State.
  2325. bool reachTerminalState = false;
  2326. DateTimeToken dtok = new DateTimeToken(); // The buffer to store the parsing token.
  2327. dtok.suffix = TokenType.SEP_Unk;
  2328. DateTimeRawInfo raw = new DateTimeRawInfo(); // The buffer to store temporary parsing information.
  2329. unsafe
  2330. {
  2331. int* numberPointer = stackalloc int[3];
  2332. raw.Init(numberPointer);
  2333. }
  2334. raw.hasSameDateAndTimeSeparators = dtfi.DateSeparator.Equals(dtfi.TimeSeparator, StringComparison.Ordinal);
  2335. result.calendar = dtfi.Calendar;
  2336. result.era = Calendar.CurrentEra;
  2337. //
  2338. // The string to be parsed. Use a __DTString wrapper so that we can trace the index which
  2339. // indicates the begining of next token.
  2340. //
  2341. __DTString str = new __DTString(s, dtfi);
  2342. str.GetNext();
  2343. //
  2344. // The following loop will break out when we reach the end of the str.
  2345. //
  2346. do
  2347. {
  2348. //
  2349. // Call the lexer to get the next token.
  2350. //
  2351. // If we find a era in Lex(), the era value will be in raw.era.
  2352. if (!Lex(dps, ref str, ref dtok, ref raw, ref result, ref dtfi, styles))
  2353. {
  2354. TPTraceExit("0000", dps);
  2355. return false;
  2356. }
  2357. //
  2358. // If the token is not unknown, process it.
  2359. // Otherwise, just discard it.
  2360. //
  2361. if (dtok.dtt != DTT.Unk)
  2362. {
  2363. //
  2364. // Check if we got any CJK Date/Time suffix.
  2365. // Since the Date/Time suffix tells us the number belongs to year/month/day/hour/minute/second,
  2366. // store the number in the appropriate field in the result.
  2367. //
  2368. if (dtok.suffix != TokenType.SEP_Unk)
  2369. {
  2370. if (!ProcessDateTimeSuffix(ref result, ref raw, ref dtok))
  2371. {
  2372. result.SetBadDateTimeFailure();
  2373. TPTraceExit("0010", dps);
  2374. return false;
  2375. }
  2376. dtok.suffix = TokenType.SEP_Unk; // Reset suffix to SEP_Unk;
  2377. }
  2378. if (dtok.dtt == DTT.NumLocalTimeMark)
  2379. {
  2380. if (dps == DS.D_YNd || dps == DS.D_YN)
  2381. {
  2382. // Consider this as ISO 8601 format:
  2383. // "yyyy-MM-dd'T'HH:mm:ss" 1999-10-31T02:00:00
  2384. TPTraceExit("0020", dps);
  2385. return (ParseISO8601(ref raw, ref str, styles, ref result));
  2386. }
  2387. else
  2388. {
  2389. result.SetBadDateTimeFailure();
  2390. TPTraceExit("0030", dps);
  2391. return false;
  2392. }
  2393. }
  2394. if (raw.hasSameDateAndTimeSeparators)
  2395. {
  2396. if (dtok.dtt == DTT.YearEnd || dtok.dtt == DTT.YearSpace || dtok.dtt == DTT.YearDateSep)
  2397. {
  2398. // When time and date separators are same and we are hitting a year number while the first parsed part of the string was recognized
  2399. // as part of time (and not a date) DS.T_Nt, DS.T_NNt then change the state to be a date so we try to parse it as a date instead
  2400. if (dps == DS.T_Nt)
  2401. {
  2402. dps = DS.D_Nd;
  2403. }
  2404. if (dps == DS.T_NNt)
  2405. {
  2406. dps = DS.D_NNd;
  2407. }
  2408. }
  2409. bool atEnd = str.AtEnd();
  2410. if (dateParsingStates[(int)dps][(int)dtok.dtt] == DS.ERROR || atEnd)
  2411. {
  2412. switch (dtok.dtt)
  2413. {
  2414. // we have the case of Serbia have dates in forms 'd.M.yyyy.' so we can expect '.' after the date parts.
  2415. // changing the token to end with space instead of Date Separator will avoid failing the parsing.
  2416. case DTT.YearDateSep: dtok.dtt = atEnd ? DTT.YearEnd : DTT.YearSpace; break;
  2417. case DTT.NumDatesep: dtok.dtt = atEnd ? DTT.NumEnd : DTT.NumSpace; break;
  2418. case DTT.NumTimesep: dtok.dtt = atEnd ? DTT.NumEnd : DTT.NumSpace; break;
  2419. case DTT.MonthDatesep: dtok.dtt = atEnd ? DTT.MonthEnd : DTT.MonthSpace; break;
  2420. }
  2421. }
  2422. }
  2423. //
  2424. // Advance to the next state, and continue
  2425. //
  2426. dps = dateParsingStates[(int)dps][(int)dtok.dtt];
  2427. if (dps == DS.ERROR)
  2428. {
  2429. result.SetBadDateTimeFailure();
  2430. TPTraceExit("0040 (invalid state transition)", dps);
  2431. return false;
  2432. }
  2433. else if (dps > DS.ERROR)
  2434. {
  2435. if ((dtfi.FormatFlags & DateTimeFormatFlags.UseHebrewRule) != 0)
  2436. {
  2437. if (!ProcessHebrewTerminalState(dps, ref str, ref result, ref styles, ref raw, dtfi))
  2438. {
  2439. TPTraceExit("0050 (ProcessHebrewTerminalState)", dps);
  2440. return false;
  2441. }
  2442. }
  2443. else
  2444. {
  2445. if (!ProcessTerminalState(dps, ref str, ref result, ref styles, ref raw, dtfi))
  2446. {
  2447. TPTraceExit("0060 (ProcessTerminalState)", dps);
  2448. return false;
  2449. }
  2450. }
  2451. reachTerminalState = true;
  2452. //
  2453. // If we have reached a terminal state, start over from DS.BEGIN again.
  2454. // For example, when we parsed "1999-12-23 13:30", we will reach a terminal state at "1999-12-23",
  2455. // and we start over so we can continue to parse "12:30".
  2456. //
  2457. dps = DS.BEGIN;
  2458. }
  2459. }
  2460. } while (dtok.dtt != DTT.End && dtok.dtt != DTT.NumEnd && dtok.dtt != DTT.MonthEnd);
  2461. if (!reachTerminalState)
  2462. {
  2463. result.SetBadDateTimeFailure();
  2464. TPTraceExit("0070 (did not reach terminal state)", dps);
  2465. return false;
  2466. }
  2467. AdjustTimeMark(dtfi, ref raw);
  2468. if (!AdjustHour(ref result.Hour, raw.timeMark))
  2469. {
  2470. result.SetBadDateTimeFailure();
  2471. TPTraceExit("0080 (AdjustHour)", dps);
  2472. return false;
  2473. }
  2474. // Check if the parsed string only contains hour/minute/second values.
  2475. bool bTimeOnly = (result.Year == -1 && result.Month == -1 && result.Day == -1);
  2476. //
  2477. // Check if any year/month/day is missing in the parsing string.
  2478. // If yes, get the default value from today's date.
  2479. //
  2480. if (!CheckDefaultDateTime(ref result, ref result.calendar, styles))
  2481. {
  2482. TPTraceExit("0090 (failed to fill in missing year/month/day defaults)", dps);
  2483. return false;
  2484. }
  2485. if (!result.calendar.TryToDateTime(result.Year, result.Month, result.Day,
  2486. result.Hour, result.Minute, result.Second, 0, result.era, out time))
  2487. {
  2488. result.SetFailure(ParseFailureKind.FormatBadDateTimeCalendar, nameof(SR.Format_BadDateTimeCalendar));
  2489. TPTraceExit("0100 (result.calendar.TryToDateTime)", dps);
  2490. return false;
  2491. }
  2492. if (raw.fraction > 0)
  2493. {
  2494. if (!time.TryAddTicks((long)Math.Round(raw.fraction * Calendar.TicksPerSecond), out time))
  2495. {
  2496. result.SetBadDateTimeFailure();
  2497. TPTraceExit("0100 (time.TryAddTicks)", dps);
  2498. return false;
  2499. }
  2500. }
  2501. //
  2502. // We have to check day of week before we adjust to the time zone.
  2503. // Otherwise, the value of day of week may change after adjusting to the time zone.
  2504. //
  2505. if (raw.dayOfWeek != -1)
  2506. {
  2507. //
  2508. // Check if day of week is correct.
  2509. //
  2510. if (raw.dayOfWeek != (int)result.calendar.GetDayOfWeek(time))
  2511. {
  2512. result.SetFailure(ParseFailureKind.FormatWithOriginalDateTime, nameof(SR.Format_BadDayOfWeek));
  2513. TPTraceExit("0110 (dayOfWeek check)", dps);
  2514. return false;
  2515. }
  2516. }
  2517. result.parsedDate = time;
  2518. if (!DetermineTimeZoneAdjustments(ref result, styles, bTimeOnly))
  2519. {
  2520. TPTraceExit("0120 (DetermineTimeZoneAdjustments)", dps);
  2521. return false;
  2522. }
  2523. TPTraceExit("0130 (success)", dps);
  2524. return true;
  2525. }
  2526. // Handles time zone adjustments and sets DateTimeKind values as required by the styles
  2527. private static bool DetermineTimeZoneAdjustments(ref DateTimeResult result, DateTimeStyles styles, bool bTimeOnly)
  2528. {
  2529. if ((result.flags & ParseFlags.CaptureOffset) != 0)
  2530. {
  2531. // This is a DateTimeOffset parse, so the offset will actually be captured directly, and
  2532. // no adjustment is required in most cases
  2533. return DateTimeOffsetTimeZonePostProcessing(ref result, styles);
  2534. }
  2535. else
  2536. {
  2537. long offsetTicks = result.timeZoneOffset.Ticks;
  2538. // the DateTime offset must be within +- 14:00 hours.
  2539. if (offsetTicks < DateTimeOffset.MinOffset || offsetTicks > DateTimeOffset.MaxOffset)
  2540. {
  2541. result.SetFailure(ParseFailureKind.FormatWithOriginalDateTime, nameof(SR.Format_OffsetOutOfRange));
  2542. return false;
  2543. }
  2544. }
  2545. // The flags AssumeUniveral and AssumeLocal only apply when the input does not have a time zone
  2546. if ((result.flags & ParseFlags.TimeZoneUsed) == 0)
  2547. {
  2548. // If AssumeLocal or AssumeLocal is used, there will always be a kind specified. As in the
  2549. // case when a time zone is present, it will default to being local unless AdjustToUniversal
  2550. // is present. These comparisons determine whether setting the kind is sufficient, or if a
  2551. // time zone adjustment is required. For consistentcy with the rest of parsing, it is desirable
  2552. // to fall through to the Adjust methods below, so that there is consist handling of boundary
  2553. // cases like wrapping around on time-only dates and temporarily allowing an adjusted date
  2554. // to exceed DateTime.MaxValue
  2555. if ((styles & DateTimeStyles.AssumeLocal) != 0)
  2556. {
  2557. if ((styles & DateTimeStyles.AdjustToUniversal) != 0)
  2558. {
  2559. result.flags |= ParseFlags.TimeZoneUsed;
  2560. result.timeZoneOffset = TimeZoneInfo.GetLocalUtcOffset(result.parsedDate, TimeZoneInfoOptions.NoThrowOnInvalidTime);
  2561. }
  2562. else
  2563. {
  2564. result.parsedDate = DateTime.SpecifyKind(result.parsedDate, DateTimeKind.Local);
  2565. return true;
  2566. }
  2567. }
  2568. else if ((styles & DateTimeStyles.AssumeUniversal) != 0)
  2569. {
  2570. if ((styles & DateTimeStyles.AdjustToUniversal) != 0)
  2571. {
  2572. result.parsedDate = DateTime.SpecifyKind(result.parsedDate, DateTimeKind.Utc);
  2573. return true;
  2574. }
  2575. else
  2576. {
  2577. result.flags |= ParseFlags.TimeZoneUsed;
  2578. result.timeZoneOffset = TimeSpan.Zero;
  2579. }
  2580. }
  2581. else
  2582. {
  2583. // No time zone and no Assume flags, so DateTimeKind.Unspecified is fine
  2584. Debug.Assert(result.parsedDate.Kind == DateTimeKind.Unspecified, "result.parsedDate.Kind == DateTimeKind.Unspecified");
  2585. return true;
  2586. }
  2587. }
  2588. if (((styles & DateTimeStyles.RoundtripKind) != 0) && ((result.flags & ParseFlags.TimeZoneUtc) != 0))
  2589. {
  2590. result.parsedDate = DateTime.SpecifyKind(result.parsedDate, DateTimeKind.Utc);
  2591. return true;
  2592. }
  2593. if ((styles & DateTimeStyles.AdjustToUniversal) != 0)
  2594. {
  2595. return (AdjustTimeZoneToUniversal(ref result));
  2596. }
  2597. return (AdjustTimeZoneToLocal(ref result, bTimeOnly));
  2598. }
  2599. // Apply validation and adjustments specific to DateTimeOffset
  2600. private static bool DateTimeOffsetTimeZonePostProcessing(ref DateTimeResult result, DateTimeStyles styles)
  2601. {
  2602. // For DateTimeOffset, default to the Utc or Local offset when an offset was not specified by
  2603. // the input string.
  2604. if ((result.flags & ParseFlags.TimeZoneUsed) == 0)
  2605. {
  2606. if ((styles & DateTimeStyles.AssumeUniversal) != 0)
  2607. {
  2608. // AssumeUniversal causes the offset to default to zero (0)
  2609. result.timeZoneOffset = TimeSpan.Zero;
  2610. }
  2611. else
  2612. {
  2613. // AssumeLocal causes the offset to default to Local. This flag is on by default for DateTimeOffset.
  2614. result.timeZoneOffset = TimeZoneInfo.GetLocalUtcOffset(result.parsedDate, TimeZoneInfoOptions.NoThrowOnInvalidTime);
  2615. }
  2616. }
  2617. long offsetTicks = result.timeZoneOffset.Ticks;
  2618. // there should be no overflow, because the offset can be no more than -+100 hours and the date already
  2619. // fits within a DateTime.
  2620. long utcTicks = result.parsedDate.Ticks - offsetTicks;
  2621. // For DateTimeOffset, both the parsed time and the corresponding UTC value must be within the boundaries
  2622. // of a DateTime instance.
  2623. if (utcTicks < DateTime.MinTicks || utcTicks > DateTime.MaxTicks)
  2624. {
  2625. result.SetFailure(ParseFailureKind.FormatWithOriginalDateTime, nameof(SR.Format_UTCOutOfRange));
  2626. return false;
  2627. }
  2628. // the offset must be within +- 14:00 hours.
  2629. if (offsetTicks < DateTimeOffset.MinOffset || offsetTicks > DateTimeOffset.MaxOffset)
  2630. {
  2631. result.SetFailure(ParseFailureKind.FormatWithOriginalDateTime, nameof(SR.Format_OffsetOutOfRange));
  2632. return false;
  2633. }
  2634. // DateTimeOffset should still honor the AdjustToUniversal flag for consistency with DateTime. It means you
  2635. // want to return an adjusted UTC value, so store the utcTicks in the DateTime and set the offset to zero
  2636. if ((styles & DateTimeStyles.AdjustToUniversal) != 0)
  2637. {
  2638. if (((result.flags & ParseFlags.TimeZoneUsed) == 0) && ((styles & DateTimeStyles.AssumeUniversal) == 0))
  2639. {
  2640. // Handle the special case where the timeZoneOffset was defaulted to Local
  2641. bool toUtcResult = AdjustTimeZoneToUniversal(ref result);
  2642. result.timeZoneOffset = TimeSpan.Zero;
  2643. return toUtcResult;
  2644. }
  2645. // The constructor should always succeed because of the range check earlier in the function
  2646. // Although it is UTC, internally DateTimeOffset does not use this flag
  2647. result.parsedDate = new DateTime(utcTicks, DateTimeKind.Utc);
  2648. result.timeZoneOffset = TimeSpan.Zero;
  2649. }
  2650. return true;
  2651. }
  2652. //
  2653. // Adjust the specified time to universal time based on the supplied timezone.
  2654. // E.g. when parsing "2001/06/08 14:00-07:00",
  2655. // the time is 2001/06/08 14:00, and timeZoneOffset = -07:00.
  2656. // The result will be "2001/06/08 21:00"
  2657. //
  2658. private static bool AdjustTimeZoneToUniversal(ref DateTimeResult result)
  2659. {
  2660. long resultTicks = result.parsedDate.Ticks;
  2661. resultTicks -= result.timeZoneOffset.Ticks;
  2662. if (resultTicks < 0)
  2663. {
  2664. resultTicks += Calendar.TicksPerDay;
  2665. }
  2666. if (resultTicks < DateTime.MinTicks || resultTicks > DateTime.MaxTicks)
  2667. {
  2668. result.SetFailure(ParseFailureKind.FormatWithOriginalDateTime, nameof(SR.Format_DateOutOfRange));
  2669. return false;
  2670. }
  2671. result.parsedDate = new DateTime(resultTicks, DateTimeKind.Utc);
  2672. return true;
  2673. }
  2674. //
  2675. // Adjust the specified time to universal time based on the supplied timezone,
  2676. // and then convert to local time.
  2677. // E.g. when parsing "2001/06/08 14:00-04:00", and local timezone is GMT-7.
  2678. // the time is 2001/06/08 14:00, and timeZoneOffset = -05:00.
  2679. // The result will be "2001/06/08 11:00"
  2680. //
  2681. private static bool AdjustTimeZoneToLocal(ref DateTimeResult result, bool bTimeOnly)
  2682. {
  2683. long resultTicks = result.parsedDate.Ticks;
  2684. // Convert to local ticks
  2685. TimeZoneInfo tz = TimeZoneInfo.Local;
  2686. bool isAmbiguousLocalDst = false;
  2687. if (resultTicks < Calendar.TicksPerDay)
  2688. {
  2689. //
  2690. // This is time of day.
  2691. //
  2692. // Adjust timezone.
  2693. resultTicks -= result.timeZoneOffset.Ticks;
  2694. // If the time is time of day, use the current timezone offset.
  2695. resultTicks += tz.GetUtcOffset(bTimeOnly ? DateTime.Now : result.parsedDate, TimeZoneInfoOptions.NoThrowOnInvalidTime).Ticks;
  2696. if (resultTicks < 0)
  2697. {
  2698. resultTicks += Calendar.TicksPerDay;
  2699. }
  2700. }
  2701. else
  2702. {
  2703. // Adjust timezone to GMT.
  2704. resultTicks -= result.timeZoneOffset.Ticks;
  2705. if (resultTicks < DateTime.MinTicks || resultTicks > DateTime.MaxTicks)
  2706. {
  2707. // If the result ticks is greater than DateTime.MaxValue, we can not create a DateTime from this ticks.
  2708. // In this case, keep using the old code.
  2709. resultTicks += tz.GetUtcOffset(result.parsedDate, TimeZoneInfoOptions.NoThrowOnInvalidTime).Ticks;
  2710. }
  2711. else
  2712. {
  2713. // Convert the GMT time to local time.
  2714. DateTime utcDt = new DateTime(resultTicks, DateTimeKind.Utc);
  2715. bool isDaylightSavings = false;
  2716. resultTicks += TimeZoneInfo.GetUtcOffsetFromUtc(utcDt, TimeZoneInfo.Local, out isDaylightSavings, out isAmbiguousLocalDst).Ticks;
  2717. }
  2718. }
  2719. if (resultTicks < DateTime.MinTicks || resultTicks > DateTime.MaxTicks)
  2720. {
  2721. result.parsedDate = DateTime.MinValue;
  2722. result.SetFailure(ParseFailureKind.FormatWithOriginalDateTime, nameof(SR.Format_DateOutOfRange));
  2723. return false;
  2724. }
  2725. result.parsedDate = new DateTime(resultTicks, DateTimeKind.Local, isAmbiguousLocalDst);
  2726. return true;
  2727. }
  2728. //
  2729. // Parse the ISO8601 format string found during Parse();
  2730. //
  2731. //
  2732. private static bool ParseISO8601(ref DateTimeRawInfo raw, ref __DTString str, DateTimeStyles styles, ref DateTimeResult result)
  2733. {
  2734. if (raw.year < 0 || raw.GetNumber(0) < 0 || raw.GetNumber(1) < 0)
  2735. {
  2736. }
  2737. str.Index--;
  2738. int hour, minute;
  2739. int second = 0;
  2740. double partSecond = 0;
  2741. str.SkipWhiteSpaces();
  2742. if (!ParseDigits(ref str, 2, out hour))
  2743. {
  2744. result.SetBadDateTimeFailure();
  2745. return false;
  2746. }
  2747. str.SkipWhiteSpaces();
  2748. if (!str.Match(':'))
  2749. {
  2750. result.SetBadDateTimeFailure();
  2751. return false;
  2752. }
  2753. str.SkipWhiteSpaces();
  2754. if (!ParseDigits(ref str, 2, out minute))
  2755. {
  2756. result.SetBadDateTimeFailure();
  2757. return false;
  2758. }
  2759. str.SkipWhiteSpaces();
  2760. if (str.Match(':'))
  2761. {
  2762. str.SkipWhiteSpaces();
  2763. if (!ParseDigits(ref str, 2, out second))
  2764. {
  2765. result.SetBadDateTimeFailure();
  2766. return false;
  2767. }
  2768. if (str.Match('.'))
  2769. {
  2770. if (!ParseFraction(ref str, out partSecond))
  2771. {
  2772. result.SetBadDateTimeFailure();
  2773. return false;
  2774. }
  2775. str.Index--;
  2776. }
  2777. str.SkipWhiteSpaces();
  2778. }
  2779. if (str.GetNext())
  2780. {
  2781. char ch = str.GetChar();
  2782. if (ch == '+' || ch == '-')
  2783. {
  2784. result.flags |= ParseFlags.TimeZoneUsed;
  2785. if (!ParseTimeZone(ref str, ref result.timeZoneOffset))
  2786. {
  2787. result.SetBadDateTimeFailure();
  2788. return false;
  2789. }
  2790. }
  2791. else if (ch == 'Z' || ch == 'z')
  2792. {
  2793. result.flags |= ParseFlags.TimeZoneUsed;
  2794. result.timeZoneOffset = TimeSpan.Zero;
  2795. result.flags |= ParseFlags.TimeZoneUtc;
  2796. }
  2797. else
  2798. {
  2799. str.Index--;
  2800. }
  2801. str.SkipWhiteSpaces();
  2802. if (str.Match('#'))
  2803. {
  2804. if (!VerifyValidPunctuation(ref str))
  2805. {
  2806. result.SetBadDateTimeFailure();
  2807. return false;
  2808. }
  2809. str.SkipWhiteSpaces();
  2810. }
  2811. if (str.Match('\0'))
  2812. {
  2813. if (!VerifyValidPunctuation(ref str))
  2814. {
  2815. result.SetBadDateTimeFailure();
  2816. return false;
  2817. }
  2818. }
  2819. if (str.GetNext())
  2820. {
  2821. // If this is true, there were non-white space characters remaining in the DateTime
  2822. result.SetBadDateTimeFailure();
  2823. return false;
  2824. }
  2825. }
  2826. DateTime time;
  2827. Calendar calendar = GregorianCalendar.GetDefaultInstance();
  2828. if (!calendar.TryToDateTime(raw.year, raw.GetNumber(0), raw.GetNumber(1),
  2829. hour, minute, second, 0, result.era, out time))
  2830. {
  2831. result.SetFailure(ParseFailureKind.FormatBadDateTimeCalendar, nameof(SR.Format_BadDateTimeCalendar));
  2832. return false;
  2833. }
  2834. if (!time.TryAddTicks((long)Math.Round(partSecond * Calendar.TicksPerSecond), out time))
  2835. {
  2836. result.SetBadDateTimeFailure();
  2837. return false;
  2838. }
  2839. result.parsedDate = time;
  2840. if (!DetermineTimeZoneAdjustments(ref result, styles, false))
  2841. {
  2842. return false;
  2843. }
  2844. return true;
  2845. }
  2846. ////////////////////////////////////////////////////////////////////////
  2847. //
  2848. // Actions:
  2849. // Parse the current word as a Hebrew number.
  2850. // This is used by DateTime.ParseExact().
  2851. //
  2852. ////////////////////////////////////////////////////////////////////////
  2853. internal static bool MatchHebrewDigits(ref __DTString str, int digitLen, out int number)
  2854. {
  2855. number = 0;
  2856. // Create a context object so that we can parse the Hebrew number text character by character.
  2857. HebrewNumberParsingContext context = new HebrewNumberParsingContext(0);
  2858. // Set this to ContinueParsing so that we will run the following while loop in the first time.
  2859. HebrewNumberParsingState state = HebrewNumberParsingState.ContinueParsing;
  2860. while (state == HebrewNumberParsingState.ContinueParsing && str.GetNext())
  2861. {
  2862. state = HebrewNumber.ParseByChar(str.GetChar(), ref context);
  2863. }
  2864. if (state == HebrewNumberParsingState.FoundEndOfHebrewNumber)
  2865. {
  2866. // If we have reached a terminal state, update the result and returns.
  2867. number = context.result;
  2868. return (true);
  2869. }
  2870. // If we run out of the character before reaching FoundEndOfHebrewNumber, or
  2871. // the state is InvalidHebrewNumber or ContinueParsing, we fail to match a Hebrew number.
  2872. // Return an error.
  2873. return false;
  2874. }
  2875. /*=================================ParseDigits==================================
  2876. **Action: Parse the number string in __DTString that are formatted using
  2877. ** the following patterns:
  2878. ** "0", "00", and "000..0"
  2879. **Returns: the integer value
  2880. **Arguments: str: a __DTString. The parsing will start from the
  2881. ** next character after str.Index.
  2882. **Exceptions: FormatException if error in parsing number.
  2883. ==============================================================================*/
  2884. internal static bool ParseDigits(ref __DTString str, int digitLen, out int result)
  2885. {
  2886. if (digitLen == 1)
  2887. {
  2888. // 1 really means 1 or 2 for this call
  2889. return ParseDigits(ref str, 1, 2, out result);
  2890. }
  2891. else
  2892. {
  2893. return ParseDigits(ref str, digitLen, digitLen, out result);
  2894. }
  2895. }
  2896. internal static bool ParseDigits(ref __DTString str, int minDigitLen, int maxDigitLen, out int result)
  2897. {
  2898. Debug.Assert(minDigitLen > 0, "minDigitLen > 0");
  2899. Debug.Assert(maxDigitLen < 9, "maxDigitLen < 9");
  2900. Debug.Assert(minDigitLen <= maxDigitLen, "minDigitLen <= maxDigitLen");
  2901. int localResult = 0;
  2902. int startingIndex = str.Index;
  2903. int tokenLength = 0;
  2904. while (tokenLength < maxDigitLen)
  2905. {
  2906. if (!str.GetNextDigit())
  2907. {
  2908. str.Index--;
  2909. break;
  2910. }
  2911. localResult = localResult * 10 + str.GetDigit();
  2912. tokenLength++;
  2913. }
  2914. result = localResult;
  2915. if (tokenLength < minDigitLen)
  2916. {
  2917. str.Index = startingIndex;
  2918. return false;
  2919. }
  2920. return true;
  2921. }
  2922. /*=================================ParseFractionExact==================================
  2923. **Action: Parse the number string in __DTString that are formatted using
  2924. ** the following patterns:
  2925. ** "0", "00", and "000..0"
  2926. **Returns: the fraction value
  2927. **Arguments: str: a __DTString. The parsing will start from the
  2928. ** next character after str.Index.
  2929. **Exceptions: FormatException if error in parsing number.
  2930. ==============================================================================*/
  2931. private static bool ParseFractionExact(ref __DTString str, int maxDigitLen, ref double result)
  2932. {
  2933. if (!str.GetNextDigit())
  2934. {
  2935. str.Index--;
  2936. return false;
  2937. }
  2938. result = str.GetDigit();
  2939. int digitLen = 1;
  2940. for (; digitLen < maxDigitLen; digitLen++)
  2941. {
  2942. if (!str.GetNextDigit())
  2943. {
  2944. str.Index--;
  2945. break;
  2946. }
  2947. result = result * 10 + str.GetDigit();
  2948. }
  2949. result /= TimeSpanParse.Pow10(digitLen);
  2950. return (digitLen == maxDigitLen);
  2951. }
  2952. /*=================================ParseSign==================================
  2953. **Action: Parse a positive or a negative sign.
  2954. **Returns: true if postive sign. flase if negative sign.
  2955. **Arguments: str: a __DTString. The parsing will start from the
  2956. ** next character after str.Index.
  2957. **Exceptions: FormatException if end of string is encountered or a sign
  2958. ** symbol is not found.
  2959. ==============================================================================*/
  2960. private static bool ParseSign(ref __DTString str, ref bool result)
  2961. {
  2962. if (!str.GetNext())
  2963. {
  2964. // A sign symbol ('+' or '-') is expected. However, end of string is encountered.
  2965. return false;
  2966. }
  2967. char ch = str.GetChar();
  2968. if (ch == '+')
  2969. {
  2970. result = true;
  2971. return (true);
  2972. }
  2973. else if (ch == '-')
  2974. {
  2975. result = false;
  2976. return (true);
  2977. }
  2978. // A sign symbol ('+' or '-') is expected.
  2979. return false;
  2980. }
  2981. /*=================================ParseTimeZoneOffset==================================
  2982. **Action: Parse the string formatted using "z", "zz", "zzz" in DateTime.Format().
  2983. **Returns: the TimeSpan for the parsed timezone offset.
  2984. **Arguments: str: a __DTString. The parsing will start from the
  2985. ** next character after str.Index.
  2986. ** len: the repeated number of the "z"
  2987. **Exceptions: FormatException if errors in parsing.
  2988. ==============================================================================*/
  2989. private static bool ParseTimeZoneOffset(ref __DTString str, int len, ref TimeSpan result)
  2990. {
  2991. bool isPositive = true;
  2992. int hourOffset;
  2993. int minuteOffset = 0;
  2994. switch (len)
  2995. {
  2996. case 1:
  2997. case 2:
  2998. if (!ParseSign(ref str, ref isPositive))
  2999. {
  3000. return (false);
  3001. }
  3002. if (!ParseDigits(ref str, len, out hourOffset))
  3003. {
  3004. return (false);
  3005. }
  3006. break;
  3007. default:
  3008. if (!ParseSign(ref str, ref isPositive))
  3009. {
  3010. return (false);
  3011. }
  3012. // Parsing 1 digit will actually parse 1 or 2.
  3013. if (!ParseDigits(ref str, 1, out hourOffset))
  3014. {
  3015. return (false);
  3016. }
  3017. // ':' is optional.
  3018. if (str.Match(":"))
  3019. {
  3020. // Found ':'
  3021. if (!ParseDigits(ref str, 2, out minuteOffset))
  3022. {
  3023. return (false);
  3024. }
  3025. }
  3026. else
  3027. {
  3028. // Since we can not match ':', put the char back.
  3029. str.Index--;
  3030. if (!ParseDigits(ref str, 2, out minuteOffset))
  3031. {
  3032. return (false);
  3033. }
  3034. }
  3035. break;
  3036. }
  3037. if (minuteOffset < 0 || minuteOffset >= 60)
  3038. {
  3039. return false;
  3040. }
  3041. result = (new TimeSpan(hourOffset, minuteOffset, 0));
  3042. if (!isPositive)
  3043. {
  3044. result = result.Negate();
  3045. }
  3046. return (true);
  3047. }
  3048. /*=================================MatchAbbreviatedMonthName==================================
  3049. **Action: Parse the abbreviated month name from string starting at str.Index.
  3050. **Returns: A value from 1 to 12 for the first month to the twelveth month.
  3051. **Arguments: str: a __DTString. The parsing will start from the
  3052. ** next character after str.Index.
  3053. **Exceptions: FormatException if an abbreviated month name can not be found.
  3054. ==============================================================================*/
  3055. private static bool MatchAbbreviatedMonthName(ref __DTString str, DateTimeFormatInfo dtfi, ref int result)
  3056. {
  3057. int maxMatchStrLen = 0;
  3058. result = -1;
  3059. if (str.GetNext())
  3060. {
  3061. //
  3062. // Scan the month names (note that some calendars has 13 months) and find
  3063. // the matching month name which has the max string length.
  3064. // We need to do this because some cultures (e.g. "cs-CZ") which have
  3065. // abbreviated month names with the same prefix.
  3066. //
  3067. int monthsInYear = (dtfi.GetMonthName(13).Length == 0 ? 12 : 13);
  3068. for (int i = 1; i <= monthsInYear; i++)
  3069. {
  3070. string searchStr = dtfi.GetAbbreviatedMonthName(i);
  3071. int matchStrLen = searchStr.Length;
  3072. if (dtfi.HasSpacesInMonthNames
  3073. ? str.MatchSpecifiedWords(searchStr, false, ref matchStrLen)
  3074. : str.MatchSpecifiedWord(searchStr))
  3075. {
  3076. if (matchStrLen > maxMatchStrLen)
  3077. {
  3078. maxMatchStrLen = matchStrLen;
  3079. result = i;
  3080. }
  3081. }
  3082. }
  3083. // Search leap year form.
  3084. if ((dtfi.FormatFlags & DateTimeFormatFlags.UseLeapYearMonth) != 0)
  3085. {
  3086. int tempResult = str.MatchLongestWords(dtfi.internalGetLeapYearMonthNames(), ref maxMatchStrLen);
  3087. // We found a longer match in the leap year month name. Use this as the result.
  3088. // The result from MatchLongestWords is 0 ~ length of word array.
  3089. // So we increment the result by one to become the month value.
  3090. if (tempResult >= 0)
  3091. {
  3092. result = tempResult + 1;
  3093. }
  3094. }
  3095. }
  3096. if (result > 0)
  3097. {
  3098. str.Index += (maxMatchStrLen - 1);
  3099. return (true);
  3100. }
  3101. return false;
  3102. }
  3103. /*=================================MatchMonthName==================================
  3104. **Action: Parse the month name from string starting at str.Index.
  3105. **Returns: A value from 1 to 12 indicating the first month to the twelveth month.
  3106. **Arguments: str: a __DTString. The parsing will start from the
  3107. ** next character after str.Index.
  3108. **Exceptions: FormatException if a month name can not be found.
  3109. ==============================================================================*/
  3110. private static bool MatchMonthName(ref __DTString str, DateTimeFormatInfo dtfi, ref int result)
  3111. {
  3112. int maxMatchStrLen = 0;
  3113. result = -1;
  3114. if (str.GetNext())
  3115. {
  3116. //
  3117. // Scan the month names (note that some calendars has 13 months) and find
  3118. // the matching month name which has the max string length.
  3119. // We need to do this because some cultures (e.g. "vi-VN") which have
  3120. // month names with the same prefix.
  3121. //
  3122. int monthsInYear = (dtfi.GetMonthName(13).Length == 0 ? 12 : 13);
  3123. for (int i = 1; i <= monthsInYear; i++)
  3124. {
  3125. string searchStr = dtfi.GetMonthName(i);
  3126. int matchStrLen = searchStr.Length;
  3127. if (dtfi.HasSpacesInMonthNames
  3128. ? str.MatchSpecifiedWords(searchStr, false, ref matchStrLen)
  3129. : str.MatchSpecifiedWord(searchStr))
  3130. {
  3131. if (matchStrLen > maxMatchStrLen)
  3132. {
  3133. maxMatchStrLen = matchStrLen;
  3134. result = i;
  3135. }
  3136. }
  3137. }
  3138. // Search genitive form.
  3139. if ((dtfi.FormatFlags & DateTimeFormatFlags.UseGenitiveMonth) != 0)
  3140. {
  3141. int tempResult = str.MatchLongestWords(dtfi.MonthGenitiveNames, ref maxMatchStrLen);
  3142. // We found a longer match in the genitive month name. Use this as the result.
  3143. // The result from MatchLongestWords is 0 ~ length of word array.
  3144. // So we increment the result by one to become the month value.
  3145. if (tempResult >= 0)
  3146. {
  3147. result = tempResult + 1;
  3148. }
  3149. }
  3150. // Search leap year form.
  3151. if ((dtfi.FormatFlags & DateTimeFormatFlags.UseLeapYearMonth) != 0)
  3152. {
  3153. int tempResult = str.MatchLongestWords(dtfi.internalGetLeapYearMonthNames(), ref maxMatchStrLen);
  3154. // We found a longer match in the leap year month name. Use this as the result.
  3155. // The result from MatchLongestWords is 0 ~ length of word array.
  3156. // So we increment the result by one to become the month value.
  3157. if (tempResult >= 0)
  3158. {
  3159. result = tempResult + 1;
  3160. }
  3161. }
  3162. }
  3163. if (result > 0)
  3164. {
  3165. str.Index += (maxMatchStrLen - 1);
  3166. return (true);
  3167. }
  3168. return false;
  3169. }
  3170. /*=================================MatchAbbreviatedDayName==================================
  3171. **Action: Parse the abbreviated day of week name from string starting at str.Index.
  3172. **Returns: A value from 0 to 6 indicating Sunday to Saturday.
  3173. **Arguments: str: a __DTString. The parsing will start from the
  3174. ** next character after str.Index.
  3175. **Exceptions: FormatException if a abbreviated day of week name can not be found.
  3176. ==============================================================================*/
  3177. private static bool MatchAbbreviatedDayName(ref __DTString str, DateTimeFormatInfo dtfi, ref int result)
  3178. {
  3179. int maxMatchStrLen = 0;
  3180. result = -1;
  3181. if (str.GetNext())
  3182. {
  3183. for (DayOfWeek i = DayOfWeek.Sunday; i <= DayOfWeek.Saturday; i++)
  3184. {
  3185. string searchStr = dtfi.GetAbbreviatedDayName(i);
  3186. int matchStrLen = searchStr.Length;
  3187. if (dtfi.HasSpacesInDayNames
  3188. ? str.MatchSpecifiedWords(searchStr, false, ref matchStrLen)
  3189. : str.MatchSpecifiedWord(searchStr))
  3190. {
  3191. if (matchStrLen > maxMatchStrLen)
  3192. {
  3193. maxMatchStrLen = matchStrLen;
  3194. result = (int)i;
  3195. }
  3196. }
  3197. }
  3198. }
  3199. if (result >= 0)
  3200. {
  3201. str.Index += maxMatchStrLen - 1;
  3202. return (true);
  3203. }
  3204. return false;
  3205. }
  3206. /*=================================MatchDayName==================================
  3207. **Action: Parse the day of week name from string starting at str.Index.
  3208. **Returns: A value from 0 to 6 indicating Sunday to Saturday.
  3209. **Arguments: str: a __DTString. The parsing will start from the
  3210. ** next character after str.Index.
  3211. **Exceptions: FormatException if a day of week name can not be found.
  3212. ==============================================================================*/
  3213. private static bool MatchDayName(ref __DTString str, DateTimeFormatInfo dtfi, ref int result)
  3214. {
  3215. // Turkish (tr-TR) got day names with the same prefix.
  3216. int maxMatchStrLen = 0;
  3217. result = -1;
  3218. if (str.GetNext())
  3219. {
  3220. for (DayOfWeek i = DayOfWeek.Sunday; i <= DayOfWeek.Saturday; i++)
  3221. {
  3222. string searchStr = dtfi.GetDayName(i);
  3223. int matchStrLen = searchStr.Length;
  3224. if (dtfi.HasSpacesInDayNames
  3225. ? str.MatchSpecifiedWords(searchStr, false, ref matchStrLen)
  3226. : str.MatchSpecifiedWord(searchStr))
  3227. {
  3228. if (matchStrLen > maxMatchStrLen)
  3229. {
  3230. maxMatchStrLen = matchStrLen;
  3231. result = (int)i;
  3232. }
  3233. }
  3234. }
  3235. }
  3236. if (result >= 0)
  3237. {
  3238. str.Index += maxMatchStrLen - 1;
  3239. return (true);
  3240. }
  3241. return false;
  3242. }
  3243. /*=================================MatchEraName==================================
  3244. **Action: Parse era name from string starting at str.Index.
  3245. **Returns: An era value.
  3246. **Arguments: str: a __DTString. The parsing will start from the
  3247. ** next character after str.Index.
  3248. **Exceptions: FormatException if an era name can not be found.
  3249. ==============================================================================*/
  3250. private static bool MatchEraName(ref __DTString str, DateTimeFormatInfo dtfi, ref int result)
  3251. {
  3252. if (str.GetNext())
  3253. {
  3254. int[] eras = dtfi.Calendar.Eras;
  3255. if (eras != null)
  3256. {
  3257. for (int i = 0; i < eras.Length; i++)
  3258. {
  3259. string searchStr = dtfi.GetEraName(eras[i]);
  3260. if (str.MatchSpecifiedWord(searchStr))
  3261. {
  3262. str.Index += (searchStr.Length - 1);
  3263. result = eras[i];
  3264. return (true);
  3265. }
  3266. searchStr = dtfi.GetAbbreviatedEraName(eras[i]);
  3267. if (str.MatchSpecifiedWord(searchStr))
  3268. {
  3269. str.Index += (searchStr.Length - 1);
  3270. result = eras[i];
  3271. return (true);
  3272. }
  3273. }
  3274. }
  3275. }
  3276. return false;
  3277. }
  3278. /*=================================MatchTimeMark==================================
  3279. **Action: Parse the time mark (AM/PM) from string starting at str.Index.
  3280. **Returns: TM_AM or TM_PM.
  3281. **Arguments: str: a __DTString. The parsing will start from the
  3282. ** next character after str.Index.
  3283. **Exceptions: FormatException if a time mark can not be found.
  3284. ==============================================================================*/
  3285. private static bool MatchTimeMark(ref __DTString str, DateTimeFormatInfo dtfi, ref TM result)
  3286. {
  3287. result = TM.NotSet;
  3288. // In some cultures have empty strings in AM/PM mark. E.g. af-ZA (0x0436), the AM mark is "", and PM mark is "nm".
  3289. if (dtfi.AMDesignator.Length == 0)
  3290. {
  3291. result = TM.AM;
  3292. }
  3293. if (dtfi.PMDesignator.Length == 0)
  3294. {
  3295. result = TM.PM;
  3296. }
  3297. if (str.GetNext())
  3298. {
  3299. string searchStr = dtfi.AMDesignator;
  3300. if (searchStr.Length > 0)
  3301. {
  3302. if (str.MatchSpecifiedWord(searchStr))
  3303. {
  3304. // Found an AM timemark with length > 0.
  3305. str.Index += (searchStr.Length - 1);
  3306. result = TM.AM;
  3307. return (true);
  3308. }
  3309. }
  3310. searchStr = dtfi.PMDesignator;
  3311. if (searchStr.Length > 0)
  3312. {
  3313. if (str.MatchSpecifiedWord(searchStr))
  3314. {
  3315. // Found a PM timemark with length > 0.
  3316. str.Index += (searchStr.Length - 1);
  3317. result = TM.PM;
  3318. return (true);
  3319. }
  3320. }
  3321. str.Index--; // Undo the GetNext call.
  3322. }
  3323. if (result != TM.NotSet)
  3324. {
  3325. // If one of the AM/PM marks is empty string, return the result.
  3326. return (true);
  3327. }
  3328. return false;
  3329. }
  3330. /*=================================MatchAbbreviatedTimeMark==================================
  3331. **Action: Parse the abbreviated time mark (AM/PM) from string starting at str.Index.
  3332. **Returns: TM_AM or TM_PM.
  3333. **Arguments: str: a __DTString. The parsing will start from the
  3334. ** next character after str.Index.
  3335. **Exceptions: FormatException if a abbreviated time mark can not be found.
  3336. ==============================================================================*/
  3337. private static bool MatchAbbreviatedTimeMark(ref __DTString str, DateTimeFormatInfo dtfi, ref TM result)
  3338. {
  3339. // NOTENOTE : the assumption here is that abbreviated time mark is the first
  3340. // character of the AM/PM designator. If this invariant changes, we have to
  3341. // change the code below.
  3342. if (str.GetNext())
  3343. {
  3344. string amDesignator = dtfi.AMDesignator;
  3345. if (amDesignator.Length > 0 && str.GetChar() == amDesignator[0])
  3346. {
  3347. result = TM.AM;
  3348. return true;
  3349. }
  3350. string pmDesignator = dtfi.PMDesignator;
  3351. if (pmDesignator.Length > 0 && str.GetChar() == pmDesignator[0])
  3352. {
  3353. result = TM.PM;
  3354. return true;
  3355. }
  3356. }
  3357. return false;
  3358. }
  3359. /*=================================CheckNewValue==================================
  3360. **Action: Check if currentValue is initialized. If not, return the newValue.
  3361. ** If yes, check if the current value is equal to newValue. Return false
  3362. ** if they are not equal. This is used to check the case like "d" and "dd" are both
  3363. ** used to format a string.
  3364. **Returns: the correct value for currentValue.
  3365. **Arguments:
  3366. **Exceptions:
  3367. ==============================================================================*/
  3368. private static bool CheckNewValue(ref int currentValue, int newValue, char patternChar, ref DateTimeResult result)
  3369. {
  3370. if (currentValue == -1)
  3371. {
  3372. currentValue = newValue;
  3373. return (true);
  3374. }
  3375. else
  3376. {
  3377. if (newValue != currentValue)
  3378. {
  3379. result.SetFailure(ParseFailureKind.FormatWithParameter, nameof(SR.Format_RepeatDateTimePattern), patternChar);
  3380. return (false);
  3381. }
  3382. }
  3383. return (true);
  3384. }
  3385. private static DateTime GetDateTimeNow(ref DateTimeResult result, ref DateTimeStyles styles)
  3386. {
  3387. if ((result.flags & ParseFlags.CaptureOffset) != 0)
  3388. {
  3389. if ((result.flags & ParseFlags.TimeZoneUsed) != 0)
  3390. {
  3391. // use the supplied offset to calculate 'Now'
  3392. return new DateTime(DateTime.UtcNow.Ticks + result.timeZoneOffset.Ticks, DateTimeKind.Unspecified);
  3393. }
  3394. else if ((styles & DateTimeStyles.AssumeUniversal) != 0)
  3395. {
  3396. // assume the offset is Utc
  3397. return DateTime.UtcNow;
  3398. }
  3399. }
  3400. // assume the offset is Local
  3401. return DateTime.Now;
  3402. }
  3403. private static bool CheckDefaultDateTime(ref DateTimeResult result, ref Calendar cal, DateTimeStyles styles)
  3404. {
  3405. if ((result.flags & ParseFlags.CaptureOffset) != 0)
  3406. {
  3407. // DateTimeOffset.Parse should allow dates without a year, but only if there is also no time zone marker;
  3408. // e.g. "May 1 5pm" is OK, but "May 1 5pm -08:30" is not. This is somewhat pragmatic, since we would
  3409. // have to rearchitect parsing completely to allow this one case to correctly handle things like leap
  3410. // years and leap months. Is is an extremely corner case, and DateTime is basically incorrect in that
  3411. // case today.
  3412. //
  3413. // values like "11:00Z" or "11:00 -3:00" are also acceptable
  3414. //
  3415. // if ((month or day is set) and (year is not set and time zone is set))
  3416. //
  3417. if (((result.Month != -1) || (result.Day != -1))
  3418. && ((result.Year == -1 || ((result.flags & ParseFlags.YearDefault) != 0)) && (result.flags & ParseFlags.TimeZoneUsed) != 0))
  3419. {
  3420. result.SetFailure(ParseFailureKind.FormatWithOriginalDateTime, nameof(SR.Format_MissingIncompleteDate));
  3421. return false;
  3422. }
  3423. }
  3424. if ((result.Year == -1) || (result.Month == -1) || (result.Day == -1))
  3425. {
  3426. /*
  3427. The following table describes the behaviors of getting the default value
  3428. when a certain year/month/day values are missing.
  3429. An "X" means that the value exists. And "--" means that value is missing.
  3430. Year Month Day => ResultYear ResultMonth ResultDay Note
  3431. X X X Parsed year Parsed month Parsed day
  3432. X X -- Parsed Year Parsed month First day If we have year and month, assume the first day of that month.
  3433. X -- X Parsed year First month Parsed day If the month is missing, assume first month of that year.
  3434. X -- -- Parsed year First month First day If we have only the year, assume the first day of that year.
  3435. -- X X CurrentYear Parsed month Parsed day If the year is missing, assume the current year.
  3436. -- X -- CurrentYear Parsed month First day If we have only a month value, assume the current year and current day.
  3437. -- -- X CurrentYear First month Parsed day If we have only a day value, assume current year and first month.
  3438. -- -- -- CurrentYear Current month Current day So this means that if the date string only contains time, you will get current date.
  3439. */
  3440. DateTime now = GetDateTimeNow(ref result, ref styles);
  3441. if (result.Month == -1 && result.Day == -1)
  3442. {
  3443. if (result.Year == -1)
  3444. {
  3445. if ((styles & DateTimeStyles.NoCurrentDateDefault) != 0)
  3446. {
  3447. // If there is no year/month/day values, and NoCurrentDateDefault flag is used,
  3448. // set the year/month/day value to the beginning year/month/day of DateTime().
  3449. // Note we should be using Gregorian for the year/month/day.
  3450. cal = GregorianCalendar.GetDefaultInstance();
  3451. result.Year = result.Month = result.Day = 1;
  3452. }
  3453. else
  3454. {
  3455. // Year/Month/Day are all missing.
  3456. result.Year = cal.GetYear(now);
  3457. result.Month = cal.GetMonth(now);
  3458. result.Day = cal.GetDayOfMonth(now);
  3459. }
  3460. }
  3461. else
  3462. {
  3463. // Month/Day are both missing.
  3464. result.Month = 1;
  3465. result.Day = 1;
  3466. }
  3467. }
  3468. else
  3469. {
  3470. if (result.Year == -1)
  3471. {
  3472. result.Year = cal.GetYear(now);
  3473. }
  3474. if (result.Month == -1)
  3475. {
  3476. result.Month = 1;
  3477. }
  3478. if (result.Day == -1)
  3479. {
  3480. result.Day = 1;
  3481. }
  3482. }
  3483. }
  3484. // Set Hour/Minute/Second to zero if these value are not in str.
  3485. if (result.Hour == -1) result.Hour = 0;
  3486. if (result.Minute == -1) result.Minute = 0;
  3487. if (result.Second == -1) result.Second = 0;
  3488. if (result.era == -1) result.era = Calendar.CurrentEra;
  3489. return true;
  3490. }
  3491. // Expand a pre-defined format string (like "D" for long date) to the real format that
  3492. // we are going to use in the date time parsing.
  3493. // This method also set the dtfi according/parseInfo to some special pre-defined
  3494. // formats.
  3495. //
  3496. private static string ExpandPredefinedFormat(ReadOnlySpan<char> format, ref DateTimeFormatInfo dtfi, ref ParsingInfo parseInfo, ref DateTimeResult result)
  3497. {
  3498. //
  3499. // Check the format to see if we need to override the dtfi to be InvariantInfo,
  3500. // and see if we need to set up the userUniversalTime flag.
  3501. //
  3502. switch (format[0])
  3503. {
  3504. case 's': // Sortable format (in local time)
  3505. case 'o':
  3506. case 'O': // Round Trip Format
  3507. ConfigureFormatOS(ref dtfi, ref parseInfo);
  3508. break;
  3509. case 'r':
  3510. case 'R': // RFC 1123 Standard. (in Universal time)
  3511. ConfigureFormatR(ref dtfi, ref parseInfo, ref result);
  3512. break;
  3513. case 'u': // Universal time format in sortable format.
  3514. parseInfo.calendar = GregorianCalendar.GetDefaultInstance();
  3515. dtfi = DateTimeFormatInfo.InvariantInfo;
  3516. if ((result.flags & ParseFlags.CaptureOffset) != 0)
  3517. {
  3518. result.flags |= ParseFlags.UtcSortPattern;
  3519. }
  3520. break;
  3521. case 'U': // Universal time format with culture-dependent format.
  3522. parseInfo.calendar = GregorianCalendar.GetDefaultInstance();
  3523. result.flags |= ParseFlags.TimeZoneUsed;
  3524. result.timeZoneOffset = new TimeSpan(0);
  3525. result.flags |= ParseFlags.TimeZoneUtc;
  3526. if (dtfi.Calendar.GetType() != typeof(GregorianCalendar))
  3527. {
  3528. dtfi = (DateTimeFormatInfo)dtfi.Clone();
  3529. dtfi.Calendar = GregorianCalendar.GetDefaultInstance();
  3530. }
  3531. break;
  3532. }
  3533. //
  3534. // Expand the pre-defined format character to the real format from DateTimeFormatInfo.
  3535. //
  3536. return (DateTimeFormat.GetRealFormat(format, dtfi));
  3537. }
  3538. [MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
  3539. private static bool ParseJapaneseEraStart(ref __DTString str, DateTimeFormatInfo dtfi)
  3540. {
  3541. // ParseJapaneseEraStart will be called when parsing the year number. We can have dates which not listing
  3542. // the year as a number and listing it as JapaneseEraStart symbol (which means year 1).
  3543. // This will be legitimate date to recognize.
  3544. if (LocalAppContextSwitches.EnforceLegacyJapaneseDateParsing || dtfi.Calendar.ID != CalendarId.JAPAN || !str.GetNext())
  3545. return false;
  3546. if (str.m_current != DateTimeFormatInfo.JapaneseEraStart[0])
  3547. {
  3548. str.Index--;
  3549. return false;
  3550. }
  3551. return true;
  3552. }
  3553. private static void ConfigureFormatR(ref DateTimeFormatInfo dtfi, ref ParsingInfo parseInfo, ref DateTimeResult result)
  3554. {
  3555. parseInfo.calendar = GregorianCalendar.GetDefaultInstance();
  3556. dtfi = DateTimeFormatInfo.InvariantInfo;
  3557. if ((result.flags & ParseFlags.CaptureOffset) != 0)
  3558. {
  3559. result.flags |= ParseFlags.Rfc1123Pattern;
  3560. }
  3561. }
  3562. private static void ConfigureFormatOS(ref DateTimeFormatInfo dtfi, ref ParsingInfo parseInfo)
  3563. {
  3564. parseInfo.calendar = GregorianCalendar.GetDefaultInstance();
  3565. dtfi = DateTimeFormatInfo.InvariantInfo;
  3566. }
  3567. // Given a specified format character, parse and update the parsing result.
  3568. //
  3569. private static bool ParseByFormat(
  3570. ref __DTString str,
  3571. ref __DTString format,
  3572. ref ParsingInfo parseInfo,
  3573. DateTimeFormatInfo dtfi,
  3574. ref DateTimeResult result)
  3575. {
  3576. int tokenLen = 0;
  3577. int tempYear = 0, tempMonth = 0, tempDay = 0, tempDayOfWeek = 0, tempHour = 0, tempMinute = 0, tempSecond = 0;
  3578. double tempFraction = 0;
  3579. TM tempTimeMark = 0;
  3580. char ch = format.GetChar();
  3581. switch (ch)
  3582. {
  3583. case 'y':
  3584. tokenLen = format.GetRepeatCount();
  3585. bool parseResult;
  3586. if (ParseJapaneseEraStart(ref str, dtfi))
  3587. {
  3588. tempYear = 1;
  3589. parseResult = true;
  3590. }
  3591. else if (dtfi.HasForceTwoDigitYears)
  3592. {
  3593. parseResult = ParseDigits(ref str, 1, 4, out tempYear);
  3594. }
  3595. else
  3596. {
  3597. if (tokenLen <= 2)
  3598. {
  3599. parseInfo.fUseTwoDigitYear = true;
  3600. }
  3601. parseResult = ParseDigits(ref str, tokenLen, out tempYear);
  3602. }
  3603. if (!parseResult && parseInfo.fCustomNumberParser)
  3604. {
  3605. parseResult = parseInfo.parseNumberDelegate(ref str, tokenLen, out tempYear);
  3606. }
  3607. if (!parseResult)
  3608. {
  3609. result.SetBadDateTimeFailure();
  3610. return (false);
  3611. }
  3612. if (!CheckNewValue(ref result.Year, tempYear, ch, ref result))
  3613. {
  3614. return (false);
  3615. }
  3616. break;
  3617. case 'M':
  3618. tokenLen = format.GetRepeatCount();
  3619. if (tokenLen <= 2)
  3620. {
  3621. if (!ParseDigits(ref str, tokenLen, out tempMonth))
  3622. {
  3623. if (!parseInfo.fCustomNumberParser ||
  3624. !parseInfo.parseNumberDelegate(ref str, tokenLen, out tempMonth))
  3625. {
  3626. result.SetBadDateTimeFailure();
  3627. return (false);
  3628. }
  3629. }
  3630. }
  3631. else
  3632. {
  3633. if (tokenLen == 3)
  3634. {
  3635. if (!MatchAbbreviatedMonthName(ref str, dtfi, ref tempMonth))
  3636. {
  3637. result.SetBadDateTimeFailure();
  3638. return (false);
  3639. }
  3640. }
  3641. else
  3642. {
  3643. if (!MatchMonthName(ref str, dtfi, ref tempMonth))
  3644. {
  3645. result.SetBadDateTimeFailure();
  3646. return (false);
  3647. }
  3648. }
  3649. result.flags |= ParseFlags.ParsedMonthName;
  3650. }
  3651. if (!CheckNewValue(ref result.Month, tempMonth, ch, ref result))
  3652. {
  3653. return (false);
  3654. }
  3655. break;
  3656. case 'd':
  3657. // Day & Day of week
  3658. tokenLen = format.GetRepeatCount();
  3659. if (tokenLen <= 2)
  3660. {
  3661. // "d" & "dd"
  3662. if (!ParseDigits(ref str, tokenLen, out tempDay))
  3663. {
  3664. if (!parseInfo.fCustomNumberParser ||
  3665. !parseInfo.parseNumberDelegate(ref str, tokenLen, out tempDay))
  3666. {
  3667. result.SetBadDateTimeFailure();
  3668. return (false);
  3669. }
  3670. }
  3671. if (!CheckNewValue(ref result.Day, tempDay, ch, ref result))
  3672. {
  3673. return (false);
  3674. }
  3675. }
  3676. else
  3677. {
  3678. if (tokenLen == 3)
  3679. {
  3680. // "ddd"
  3681. if (!MatchAbbreviatedDayName(ref str, dtfi, ref tempDayOfWeek))
  3682. {
  3683. result.SetBadDateTimeFailure();
  3684. return (false);
  3685. }
  3686. }
  3687. else
  3688. {
  3689. // "dddd*"
  3690. if (!MatchDayName(ref str, dtfi, ref tempDayOfWeek))
  3691. {
  3692. result.SetBadDateTimeFailure();
  3693. return (false);
  3694. }
  3695. }
  3696. if (!CheckNewValue(ref parseInfo.dayOfWeek, tempDayOfWeek, ch, ref result))
  3697. {
  3698. return (false);
  3699. }
  3700. }
  3701. break;
  3702. case 'g':
  3703. tokenLen = format.GetRepeatCount();
  3704. // Put the era value in result.era.
  3705. if (!MatchEraName(ref str, dtfi, ref result.era))
  3706. {
  3707. result.SetBadDateTimeFailure();
  3708. return (false);
  3709. }
  3710. break;
  3711. case 'h':
  3712. parseInfo.fUseHour12 = true;
  3713. tokenLen = format.GetRepeatCount();
  3714. if (!ParseDigits(ref str, (tokenLen < 2 ? 1 : 2), out tempHour))
  3715. {
  3716. result.SetBadDateTimeFailure();
  3717. return (false);
  3718. }
  3719. if (!CheckNewValue(ref result.Hour, tempHour, ch, ref result))
  3720. {
  3721. return (false);
  3722. }
  3723. break;
  3724. case 'H':
  3725. tokenLen = format.GetRepeatCount();
  3726. if (!ParseDigits(ref str, (tokenLen < 2 ? 1 : 2), out tempHour))
  3727. {
  3728. result.SetBadDateTimeFailure();
  3729. return (false);
  3730. }
  3731. if (!CheckNewValue(ref result.Hour, tempHour, ch, ref result))
  3732. {
  3733. return (false);
  3734. }
  3735. break;
  3736. case 'm':
  3737. tokenLen = format.GetRepeatCount();
  3738. if (!ParseDigits(ref str, (tokenLen < 2 ? 1 : 2), out tempMinute))
  3739. {
  3740. result.SetBadDateTimeFailure();
  3741. return (false);
  3742. }
  3743. if (!CheckNewValue(ref result.Minute, tempMinute, ch, ref result))
  3744. {
  3745. return (false);
  3746. }
  3747. break;
  3748. case 's':
  3749. tokenLen = format.GetRepeatCount();
  3750. if (!ParseDigits(ref str, (tokenLen < 2 ? 1 : 2), out tempSecond))
  3751. {
  3752. result.SetBadDateTimeFailure();
  3753. return (false);
  3754. }
  3755. if (!CheckNewValue(ref result.Second, tempSecond, ch, ref result))
  3756. {
  3757. return (false);
  3758. }
  3759. break;
  3760. case 'f':
  3761. case 'F':
  3762. tokenLen = format.GetRepeatCount();
  3763. if (tokenLen <= DateTimeFormat.MaxSecondsFractionDigits)
  3764. {
  3765. if (!ParseFractionExact(ref str, tokenLen, ref tempFraction))
  3766. {
  3767. if (ch == 'f')
  3768. {
  3769. result.SetBadDateTimeFailure();
  3770. return (false);
  3771. }
  3772. }
  3773. if (result.fraction < 0)
  3774. {
  3775. result.fraction = tempFraction;
  3776. }
  3777. else
  3778. {
  3779. if (tempFraction != result.fraction)
  3780. {
  3781. result.SetFailure(ParseFailureKind.FormatWithParameter, nameof(SR.Format_RepeatDateTimePattern), ch);
  3782. return (false);
  3783. }
  3784. }
  3785. }
  3786. else
  3787. {
  3788. result.SetBadDateTimeFailure();
  3789. return (false);
  3790. }
  3791. break;
  3792. case 't':
  3793. // AM/PM designator
  3794. tokenLen = format.GetRepeatCount();
  3795. if (tokenLen == 1)
  3796. {
  3797. if (!MatchAbbreviatedTimeMark(ref str, dtfi, ref tempTimeMark))
  3798. {
  3799. result.SetBadDateTimeFailure();
  3800. return (false);
  3801. }
  3802. }
  3803. else
  3804. {
  3805. if (!MatchTimeMark(ref str, dtfi, ref tempTimeMark))
  3806. {
  3807. result.SetBadDateTimeFailure();
  3808. return (false);
  3809. }
  3810. }
  3811. if (parseInfo.timeMark == TM.NotSet)
  3812. {
  3813. parseInfo.timeMark = tempTimeMark;
  3814. }
  3815. else
  3816. {
  3817. if (parseInfo.timeMark != tempTimeMark)
  3818. {
  3819. result.SetFailure(ParseFailureKind.FormatWithParameter, nameof(SR.Format_RepeatDateTimePattern), ch);
  3820. return (false);
  3821. }
  3822. }
  3823. break;
  3824. case 'z':
  3825. // timezone offset
  3826. tokenLen = format.GetRepeatCount();
  3827. {
  3828. TimeSpan tempTimeZoneOffset = new TimeSpan(0);
  3829. if (!ParseTimeZoneOffset(ref str, tokenLen, ref tempTimeZoneOffset))
  3830. {
  3831. result.SetBadDateTimeFailure();
  3832. return (false);
  3833. }
  3834. if ((result.flags & ParseFlags.TimeZoneUsed) != 0 && tempTimeZoneOffset != result.timeZoneOffset)
  3835. {
  3836. result.SetFailure(ParseFailureKind.FormatWithParameter, nameof(SR.Format_RepeatDateTimePattern), 'z');
  3837. return (false);
  3838. }
  3839. result.timeZoneOffset = tempTimeZoneOffset;
  3840. result.flags |= ParseFlags.TimeZoneUsed;
  3841. }
  3842. break;
  3843. case 'Z':
  3844. if ((result.flags & ParseFlags.TimeZoneUsed) != 0 && result.timeZoneOffset != TimeSpan.Zero)
  3845. {
  3846. result.SetFailure(ParseFailureKind.FormatWithParameter, nameof(SR.Format_RepeatDateTimePattern), 'Z');
  3847. return (false);
  3848. }
  3849. result.flags |= ParseFlags.TimeZoneUsed;
  3850. result.timeZoneOffset = new TimeSpan(0);
  3851. result.flags |= ParseFlags.TimeZoneUtc;
  3852. // The updating of the indexes is to reflect that ParseExact MatchXXX methods assume that
  3853. // they need to increment the index and Parse GetXXX do not. Since we are calling a Parse
  3854. // method from inside ParseExact we need to adjust this. Long term, we should try to
  3855. // eliminate this discrepancy.
  3856. str.Index++;
  3857. if (!GetTimeZoneName(ref str))
  3858. {
  3859. result.SetBadDateTimeFailure();
  3860. return false;
  3861. }
  3862. str.Index--;
  3863. break;
  3864. case 'K':
  3865. // This should parse either as a blank, the 'Z' character or a local offset like "-07:00"
  3866. if (str.Match('Z'))
  3867. {
  3868. if ((result.flags & ParseFlags.TimeZoneUsed) != 0 && result.timeZoneOffset != TimeSpan.Zero)
  3869. {
  3870. result.SetFailure(ParseFailureKind.FormatWithParameter, nameof(SR.Format_RepeatDateTimePattern), 'K');
  3871. return (false);
  3872. }
  3873. result.flags |= ParseFlags.TimeZoneUsed;
  3874. result.timeZoneOffset = new TimeSpan(0);
  3875. result.flags |= ParseFlags.TimeZoneUtc;
  3876. }
  3877. else if (str.Match('+') || str.Match('-'))
  3878. {
  3879. str.Index--; // Put the character back for the parser
  3880. TimeSpan tempTimeZoneOffset = new TimeSpan(0);
  3881. if (!ParseTimeZoneOffset(ref str, 3, ref tempTimeZoneOffset))
  3882. {
  3883. result.SetBadDateTimeFailure();
  3884. return (false);
  3885. }
  3886. if ((result.flags & ParseFlags.TimeZoneUsed) != 0 && tempTimeZoneOffset != result.timeZoneOffset)
  3887. {
  3888. result.SetFailure(ParseFailureKind.FormatWithParameter, nameof(SR.Format_RepeatDateTimePattern), 'K');
  3889. return (false);
  3890. }
  3891. result.timeZoneOffset = tempTimeZoneOffset;
  3892. result.flags |= ParseFlags.TimeZoneUsed;
  3893. }
  3894. // Otherwise it is unspecified and we consume no characters
  3895. break;
  3896. case ':':
  3897. // We match the separator in time pattern with the character in the time string if both equal to ':' or the date separator is matching the characters in the date string
  3898. // We have to exclude the case when the time separator is more than one character and starts with ':' something like "::" for instance.
  3899. if (((dtfi.TimeSeparator.Length > 1 && dtfi.TimeSeparator[0] == ':') || !str.Match(':')) &&
  3900. !str.Match(dtfi.TimeSeparator))
  3901. {
  3902. // A time separator is expected.
  3903. result.SetBadDateTimeFailure();
  3904. return false;
  3905. }
  3906. break;
  3907. case '/':
  3908. // We match the separator in date pattern with the character in the date string if both equal to '/' or the date separator is matching the characters in the date string
  3909. // We have to exclude the case when the date separator is more than one character and starts with '/' something like "//" for instance.
  3910. if (((dtfi.DateSeparator.Length > 1 && dtfi.DateSeparator[0] == '/') || !str.Match('/')) &&
  3911. !str.Match(dtfi.DateSeparator))
  3912. {
  3913. // A date separator is expected.
  3914. result.SetBadDateTimeFailure();
  3915. return false;
  3916. }
  3917. break;
  3918. case '\"':
  3919. case '\'':
  3920. StringBuilder enquotedString = StringBuilderCache.Acquire();
  3921. // Use ParseQuoteString so that we can handle escape characters within the quoted string.
  3922. if (!TryParseQuoteString(format.Value, format.Index, enquotedString, out tokenLen))
  3923. {
  3924. result.SetFailure(ParseFailureKind.FormatWithParameter, nameof(SR.Format_BadQuote), ch);
  3925. StringBuilderCache.Release(enquotedString);
  3926. return (false);
  3927. }
  3928. format.Index += tokenLen - 1;
  3929. // Some cultures uses space in the quoted string. E.g. Spanish has long date format as:
  3930. // "dddd, dd' de 'MMMM' de 'yyyy". When inner spaces flag is set, we should skip whitespaces if there is space
  3931. // in the quoted string.
  3932. string quotedStr = StringBuilderCache.GetStringAndRelease(enquotedString);
  3933. for (int i = 0; i < quotedStr.Length; i++)
  3934. {
  3935. if (quotedStr[i] == ' ' && parseInfo.fAllowInnerWhite)
  3936. {
  3937. str.SkipWhiteSpaces();
  3938. }
  3939. else if (!str.Match(quotedStr[i]))
  3940. {
  3941. // Can not find the matching quoted string.
  3942. result.SetBadDateTimeFailure();
  3943. return false;
  3944. }
  3945. }
  3946. // The "r" and "u" formats incorrectly quoted 'GMT' and 'Z', respectively. We cannot
  3947. // correct this mistake for DateTime.ParseExact for compatibility reasons, but we can
  3948. // fix it for DateTimeOffset.ParseExact as DateTimeOffset has not been publically released
  3949. // with this issue.
  3950. if ((result.flags & ParseFlags.CaptureOffset) != 0)
  3951. {
  3952. if ((result.flags & ParseFlags.Rfc1123Pattern) != 0 && quotedStr == GMTName)
  3953. {
  3954. result.flags |= ParseFlags.TimeZoneUsed;
  3955. result.timeZoneOffset = TimeSpan.Zero;
  3956. }
  3957. else if ((result.flags & ParseFlags.UtcSortPattern) != 0 && quotedStr == ZuluName)
  3958. {
  3959. result.flags |= ParseFlags.TimeZoneUsed;
  3960. result.timeZoneOffset = TimeSpan.Zero;
  3961. }
  3962. }
  3963. break;
  3964. case '%':
  3965. // Skip this so we can get to the next pattern character.
  3966. // Used in case like "%d", "%y"
  3967. // Make sure the next character is not a '%' again.
  3968. if (format.Index >= format.Value.Length - 1 || format.Value[format.Index + 1] == '%')
  3969. {
  3970. result.SetBadFormatSpecifierFailure(format.Value);
  3971. return false;
  3972. }
  3973. break;
  3974. case '\\':
  3975. // Escape character. For example, "\d".
  3976. // Get the next character in format, and see if we can
  3977. // find a match in str.
  3978. if (format.GetNext())
  3979. {
  3980. if (!str.Match(format.GetChar()))
  3981. {
  3982. // Can not find a match for the escaped character.
  3983. result.SetBadDateTimeFailure();
  3984. return false;
  3985. }
  3986. }
  3987. else
  3988. {
  3989. result.SetBadFormatSpecifierFailure(format.Value);
  3990. return false;
  3991. }
  3992. break;
  3993. case '.':
  3994. if (!str.Match(ch))
  3995. {
  3996. if (format.GetNext())
  3997. {
  3998. // If we encounter the pattern ".F", and the dot is not present, it is an optional
  3999. // second fraction and we can skip this format.
  4000. if (format.Match('F'))
  4001. {
  4002. format.GetRepeatCount();
  4003. break;
  4004. }
  4005. }
  4006. result.SetBadDateTimeFailure();
  4007. return false;
  4008. }
  4009. break;
  4010. default:
  4011. if (ch == ' ')
  4012. {
  4013. if (parseInfo.fAllowInnerWhite)
  4014. {
  4015. // Skip whitespaces if AllowInnerWhite.
  4016. // Do nothing here.
  4017. }
  4018. else
  4019. {
  4020. if (!str.Match(ch))
  4021. {
  4022. // If the space does not match, and trailing space is allowed, we do
  4023. // one more step to see if the next format character can lead to
  4024. // successful parsing.
  4025. // This is used to deal with special case that a empty string can match
  4026. // a specific pattern.
  4027. // The example here is af-ZA, which has a time format like "hh:mm:ss tt". However,
  4028. // its AM symbol is "" (empty string). If fAllowTrailingWhite is used, and time is in
  4029. // the AM, we will trim the whitespaces at the end, which will lead to a failure
  4030. // when we are trying to match the space before "tt".
  4031. if (parseInfo.fAllowTrailingWhite)
  4032. {
  4033. if (format.GetNext())
  4034. {
  4035. if (ParseByFormat(ref str, ref format, ref parseInfo, dtfi, ref result))
  4036. {
  4037. return (true);
  4038. }
  4039. }
  4040. }
  4041. result.SetBadDateTimeFailure();
  4042. return false;
  4043. }
  4044. // Found a macth.
  4045. }
  4046. }
  4047. else
  4048. {
  4049. if (format.MatchSpecifiedWord(GMTName))
  4050. {
  4051. format.Index += (GMTName.Length - 1);
  4052. // Found GMT string in format. This means the DateTime string
  4053. // is in GMT timezone.
  4054. result.flags |= ParseFlags.TimeZoneUsed;
  4055. result.timeZoneOffset = TimeSpan.Zero;
  4056. if (!str.Match(GMTName))
  4057. {
  4058. result.SetBadDateTimeFailure();
  4059. return false;
  4060. }
  4061. }
  4062. else if (!str.Match(ch))
  4063. {
  4064. // ch is expected.
  4065. result.SetBadDateTimeFailure();
  4066. return false;
  4067. }
  4068. }
  4069. break;
  4070. } // switch
  4071. return (true);
  4072. }
  4073. //
  4074. // The pos should point to a quote character. This method will
  4075. // get the string enclosed by the quote character.
  4076. //
  4077. internal static bool TryParseQuoteString(ReadOnlySpan<char> format, int pos, StringBuilder result, out int returnValue)
  4078. {
  4079. //
  4080. // NOTE : pos will be the index of the quote character in the 'format' string.
  4081. //
  4082. returnValue = 0;
  4083. int formatLen = format.Length;
  4084. int beginPos = pos;
  4085. char quoteChar = format[pos++]; // Get the character used to quote the following string.
  4086. bool foundQuote = false;
  4087. while (pos < formatLen)
  4088. {
  4089. char ch = format[pos++];
  4090. if (ch == quoteChar)
  4091. {
  4092. foundQuote = true;
  4093. break;
  4094. }
  4095. else if (ch == '\\')
  4096. {
  4097. // The following are used to support escaped character.
  4098. // Escaped character is also supported in the quoted string.
  4099. // Therefore, someone can use a format like "'minute:' mm\"" to display:
  4100. // minute: 45"
  4101. // because the second double quote is escaped.
  4102. if (pos < formatLen)
  4103. {
  4104. result.Append(format[pos++]);
  4105. }
  4106. else
  4107. {
  4108. //
  4109. // This means that '\' is at the end of the formatting string.
  4110. //
  4111. return false;
  4112. }
  4113. }
  4114. else
  4115. {
  4116. result.Append(ch);
  4117. }
  4118. }
  4119. if (!foundQuote)
  4120. {
  4121. // Here we can't find the matching quote.
  4122. return false;
  4123. }
  4124. //
  4125. // Return the character count including the begin/end quote characters and enclosed string.
  4126. //
  4127. returnValue = (pos - beginPos);
  4128. return true;
  4129. }
  4130. /*=================================DoStrictParse==================================
  4131. **Action: Do DateTime parsing using the format in formatParam.
  4132. **Returns: The parsed DateTime.
  4133. **Arguments:
  4134. **Exceptions:
  4135. **
  4136. **Notes:
  4137. ** When the following general formats are used, InvariantInfo is used in dtfi:
  4138. ** 'r', 'R', 's'.
  4139. ** When the following general formats are used, the time is assumed to be in Universal time.
  4140. **
  4141. **Limitations:
  4142. ** Only GregorianCalendar is supported for now.
  4143. ** Only support GMT timezone.
  4144. ==============================================================================*/
  4145. private static bool DoStrictParse(
  4146. ReadOnlySpan<char> s,
  4147. ReadOnlySpan<char> formatParam,
  4148. DateTimeStyles styles,
  4149. DateTimeFormatInfo dtfi,
  4150. ref DateTimeResult result)
  4151. {
  4152. ParsingInfo parseInfo = new ParsingInfo();
  4153. parseInfo.Init();
  4154. parseInfo.calendar = dtfi.Calendar;
  4155. parseInfo.fAllowInnerWhite = ((styles & DateTimeStyles.AllowInnerWhite) != 0);
  4156. parseInfo.fAllowTrailingWhite = ((styles & DateTimeStyles.AllowTrailingWhite) != 0);
  4157. if (formatParam.Length == 1)
  4158. {
  4159. char formatParamChar = formatParam[0];
  4160. // Fast-paths for common and important formats/configurations.
  4161. if (styles == DateTimeStyles.None)
  4162. {
  4163. switch (formatParamChar)
  4164. {
  4165. case 'R':
  4166. case 'r':
  4167. ConfigureFormatR(ref dtfi, ref parseInfo, ref result);
  4168. return ParseFormatR(s, ref parseInfo, ref result);
  4169. case 'O':
  4170. case 'o':
  4171. ConfigureFormatOS(ref dtfi, ref parseInfo);
  4172. return ParseFormatO(s, ref parseInfo, ref result);
  4173. }
  4174. }
  4175. if (((result.flags & ParseFlags.CaptureOffset) != 0) && formatParamChar == 'U')
  4176. {
  4177. // The 'U' format is not allowed for DateTimeOffset
  4178. result.SetBadFormatSpecifierFailure(formatParam);
  4179. return false;
  4180. }
  4181. formatParam = ExpandPredefinedFormat(formatParam, ref dtfi, ref parseInfo, ref result);
  4182. }
  4183. bool bTimeOnly = false;
  4184. result.calendar = parseInfo.calendar;
  4185. if (parseInfo.calendar.ID == CalendarId.HEBREW)
  4186. {
  4187. parseInfo.parseNumberDelegate = m_hebrewNumberParser;
  4188. parseInfo.fCustomNumberParser = true;
  4189. }
  4190. // Reset these values to negative one so that we could throw exception
  4191. // if we have parsed every item twice.
  4192. result.Hour = result.Minute = result.Second = -1;
  4193. __DTString format = new __DTString(formatParam, dtfi, false);
  4194. __DTString str = new __DTString(s, dtfi, false);
  4195. if (parseInfo.fAllowTrailingWhite)
  4196. {
  4197. // Trim trailing spaces if AllowTrailingWhite.
  4198. format.TrimTail();
  4199. format.RemoveTrailingInQuoteSpaces();
  4200. str.TrimTail();
  4201. }
  4202. if ((styles & DateTimeStyles.AllowLeadingWhite) != 0)
  4203. {
  4204. format.SkipWhiteSpaces();
  4205. format.RemoveLeadingInQuoteSpaces();
  4206. str.SkipWhiteSpaces();
  4207. }
  4208. //
  4209. // Scan every character in format and match the pattern in str.
  4210. //
  4211. while (format.GetNext())
  4212. {
  4213. // We trim inner spaces here, so that we will not eat trailing spaces when
  4214. // AllowTrailingWhite is not used.
  4215. if (parseInfo.fAllowInnerWhite)
  4216. {
  4217. str.SkipWhiteSpaces();
  4218. }
  4219. if (!ParseByFormat(ref str, ref format, ref parseInfo, dtfi, ref result))
  4220. {
  4221. return (false);
  4222. }
  4223. }
  4224. if (str.Index < str.Value.Length - 1)
  4225. {
  4226. // There are still remaining character in str.
  4227. result.SetBadDateTimeFailure();
  4228. return false;
  4229. }
  4230. if (parseInfo.fUseTwoDigitYear && ((dtfi.FormatFlags & DateTimeFormatFlags.UseHebrewRule) == 0))
  4231. {
  4232. // A two digit year value is expected. Check if the parsed year value is valid.
  4233. if (result.Year >= 100)
  4234. {
  4235. result.SetBadDateTimeFailure();
  4236. return false;
  4237. }
  4238. try
  4239. {
  4240. result.Year = parseInfo.calendar.ToFourDigitYear(result.Year);
  4241. }
  4242. catch (ArgumentOutOfRangeException)
  4243. {
  4244. result.SetBadDateTimeFailure();
  4245. return false;
  4246. }
  4247. }
  4248. if (parseInfo.fUseHour12)
  4249. {
  4250. if (parseInfo.timeMark == TM.NotSet)
  4251. {
  4252. // hh is used, but no AM/PM designator is specified.
  4253. // Assume the time is AM.
  4254. // Don't throw exceptions in here becasue it is very confusing for the caller.
  4255. // I always got confused myself when I use "hh:mm:ss" to parse a time string,
  4256. // and ParseExact() throws on me (because I didn't use the 24-hour clock 'HH').
  4257. parseInfo.timeMark = TM.AM;
  4258. }
  4259. if (result.Hour > 12)
  4260. {
  4261. // AM/PM is used, but the value for HH is too big.
  4262. result.SetBadDateTimeFailure();
  4263. return false;
  4264. }
  4265. if (parseInfo.timeMark == TM.AM)
  4266. {
  4267. if (result.Hour == 12)
  4268. {
  4269. result.Hour = 0;
  4270. }
  4271. }
  4272. else
  4273. {
  4274. result.Hour = (result.Hour == 12) ? 12 : result.Hour + 12;
  4275. }
  4276. }
  4277. else
  4278. {
  4279. // Military (24-hour time) mode
  4280. //
  4281. // AM cannot be set with a 24-hour time like 17:15.
  4282. // PM cannot be set with a 24-hour time like 03:15.
  4283. if ((parseInfo.timeMark == TM.AM && result.Hour >= 12)
  4284. || (parseInfo.timeMark == TM.PM && result.Hour < 12))
  4285. {
  4286. result.SetBadDateTimeFailure();
  4287. return false;
  4288. }
  4289. }
  4290. // Check if the parsed string only contains hour/minute/second values.
  4291. bTimeOnly = (result.Year == -1 && result.Month == -1 && result.Day == -1);
  4292. if (!CheckDefaultDateTime(ref result, ref parseInfo.calendar, styles))
  4293. {
  4294. return false;
  4295. }
  4296. if (!bTimeOnly && dtfi.HasYearMonthAdjustment)
  4297. {
  4298. if (!dtfi.YearMonthAdjustment(ref result.Year, ref result.Month, ((result.flags & ParseFlags.ParsedMonthName) != 0)))
  4299. {
  4300. result.SetFailure(ParseFailureKind.FormatBadDateTimeCalendar, nameof(SR.Format_BadDateTimeCalendar));
  4301. return false;
  4302. }
  4303. }
  4304. if (!parseInfo.calendar.TryToDateTime(result.Year, result.Month, result.Day,
  4305. result.Hour, result.Minute, result.Second, 0, result.era, out result.parsedDate))
  4306. {
  4307. result.SetFailure(ParseFailureKind.FormatBadDateTimeCalendar, nameof(SR.Format_BadDateTimeCalendar));
  4308. return false;
  4309. }
  4310. if (result.fraction > 0)
  4311. {
  4312. if (!result.parsedDate.TryAddTicks((long)Math.Round(result.fraction * Calendar.TicksPerSecond), out result.parsedDate))
  4313. {
  4314. result.SetBadDateTimeFailure();
  4315. return false;
  4316. }
  4317. }
  4318. //
  4319. // We have to check day of week before we adjust to the time zone.
  4320. // It is because the value of day of week may change after adjusting
  4321. // to the time zone.
  4322. //
  4323. if (parseInfo.dayOfWeek != -1)
  4324. {
  4325. //
  4326. // Check if day of week is correct.
  4327. //
  4328. if (parseInfo.dayOfWeek != (int)parseInfo.calendar.GetDayOfWeek(result.parsedDate))
  4329. {
  4330. result.SetFailure(ParseFailureKind.FormatWithOriginalDateTime, nameof(SR.Format_BadDayOfWeek));
  4331. return false;
  4332. }
  4333. }
  4334. if (!DetermineTimeZoneAdjustments(ref result, styles, bTimeOnly))
  4335. {
  4336. return false;
  4337. }
  4338. return true;
  4339. }
  4340. private static bool ParseFormatR(ReadOnlySpan<char> source, ref ParsingInfo parseInfo, ref DateTimeResult result)
  4341. {
  4342. // Example:
  4343. // Tue, 03 Jan 2017 08:08:05 GMT
  4344. // The format is exactly 29 characters.
  4345. if ((uint)source.Length != 29)
  4346. {
  4347. result.SetBadDateTimeFailure();
  4348. return false;
  4349. }
  4350. // Parse the three-letter day of week. Any casing is valid.
  4351. DayOfWeek dayOfWeek;
  4352. {
  4353. uint dow0 = source[0], dow1 = source[1], dow2 = source[2], comma = source[3];
  4354. if ((dow0 | dow1 | dow2 | comma) > 0x7F)
  4355. {
  4356. result.SetBadDateTimeFailure();
  4357. return false;
  4358. }
  4359. uint dowString = (dow0 << 24) | (dow1 << 16) | (dow2 << 8) | comma | 0x20202000;
  4360. switch (dowString)
  4361. {
  4362. case 0x73756E2c /* 'sun,' */: dayOfWeek = DayOfWeek.Sunday; break;
  4363. case 0x6d6f6e2c /* 'mon,' */: dayOfWeek = DayOfWeek.Monday; break;
  4364. case 0x7475652c /* 'tue,' */: dayOfWeek = DayOfWeek.Tuesday; break;
  4365. case 0x7765642c /* 'wed,' */: dayOfWeek = DayOfWeek.Wednesday; break;
  4366. case 0x7468752c /* 'thu,' */: dayOfWeek = DayOfWeek.Thursday; break;
  4367. case 0x6672692c /* 'fri,' */: dayOfWeek = DayOfWeek.Friday; break;
  4368. case 0x7361742c /* 'sat,' */: dayOfWeek = DayOfWeek.Saturday; break;
  4369. default:
  4370. result.SetBadDateTimeFailure();
  4371. return false;
  4372. }
  4373. }
  4374. if (source[4] != ' ')
  4375. {
  4376. result.SetBadDateTimeFailure();
  4377. return false;
  4378. }
  4379. // Parse the two digit day.
  4380. int day;
  4381. {
  4382. uint digit1 = (uint)(source[5] - '0'), digit2 = (uint)(source[6] - '0');
  4383. if (digit1 > 9 || digit2 > 9)
  4384. {
  4385. result.SetBadDateTimeFailure();
  4386. return false;
  4387. }
  4388. day = (int)(digit1*10 + digit2);
  4389. }
  4390. if (source[7] != ' ')
  4391. {
  4392. result.SetBadDateTimeFailure();
  4393. return false;
  4394. }
  4395. // Parse the three letter month (followed by a space). Any casing is valid.
  4396. int month;
  4397. {
  4398. uint m0 = source[8], m1 = source[9], m2 = source[10], space = source[11];
  4399. if ((m0 | m1 | m2 | space) > 0x7F)
  4400. {
  4401. result.SetBadDateTimeFailure();
  4402. return false;
  4403. }
  4404. switch ((m0 << 24) | (m1 << 16) | (m2 << 8) | space | 0x20202000)
  4405. {
  4406. case 0x6a616e20 /* 'jan ' */ : month = 1; break;
  4407. case 0x66656220 /* 'feb ' */ : month = 2; break;
  4408. case 0x6d617220 /* 'mar ' */ : month = 3; break;
  4409. case 0x61707220 /* 'apr ' */ : month = 4; break;
  4410. case 0x6d617920 /* 'may ' */ : month = 5; break;
  4411. case 0x6a756e20 /* 'jun ' */ : month = 6; break;
  4412. case 0x6a756c20 /* 'jul ' */ : month = 7; break;
  4413. case 0x61756720 /* 'aug ' */ : month = 8; break;
  4414. case 0x73657020 /* 'sep ' */ : month = 9; break;
  4415. case 0x6f637420 /* 'oct ' */ : month = 10; break;
  4416. case 0x6e6f7620 /* 'nov ' */ : month = 11; break;
  4417. case 0x64656320 /* 'dec ' */ : month = 12; break;
  4418. default:
  4419. result.SetBadDateTimeFailure();
  4420. return false;
  4421. }
  4422. }
  4423. // Parse the four-digit year.
  4424. int year;
  4425. {
  4426. uint y1 = (uint)(source[12] - '0'), y2 = (uint)(source[13] - '0'), y3 = (uint)(source[14] - '0'), y4 = (uint)(source[15] - '0');
  4427. if (y1 > 9 || y2 > 9 || y3 > 9 || y4 > 9)
  4428. {
  4429. result.SetBadDateTimeFailure();
  4430. return false;
  4431. }
  4432. year = (int)(y1*1000 + y2*100 + y3*10 + y4);
  4433. }
  4434. if (source[16] != ' ')
  4435. {
  4436. result.SetBadDateTimeFailure();
  4437. return false;
  4438. }
  4439. // Parse the two digit hour.
  4440. int hour;
  4441. {
  4442. uint h1 = (uint)(source[17] - '0'), h2 = (uint)(source[18] - '0');
  4443. if (h1 > 9 || h2 > 9)
  4444. {
  4445. result.SetBadDateTimeFailure();
  4446. return false;
  4447. }
  4448. hour = (int)(h1*10 + h2);
  4449. }
  4450. if (source[19] != ':')
  4451. {
  4452. result.SetBadDateTimeFailure();
  4453. return false;
  4454. }
  4455. // Parse the two-digit minute.
  4456. int minute;
  4457. {
  4458. uint m1 = (uint)(source[20] - '0');
  4459. uint m2 = (uint)(source[21] - '0');
  4460. if (m1 > 9 || m2 > 9)
  4461. {
  4462. result.SetBadDateTimeFailure();
  4463. return false;
  4464. }
  4465. minute = (int)(m1*10 + m2);
  4466. }
  4467. if (source[22] != ':')
  4468. {
  4469. result.SetBadDateTimeFailure();
  4470. return false;
  4471. }
  4472. // Parse the two-digit second.
  4473. int second;
  4474. {
  4475. uint s1 = (uint)(source[23] - '0'), s2 = (uint)(source[24] - '0');
  4476. if (s1 > 9 || s2 > 9)
  4477. {
  4478. result.SetBadDateTimeFailure();
  4479. return false;
  4480. }
  4481. second = (int)(s1*10 + s2);
  4482. }
  4483. // Parse " GMT". It must be upper case.
  4484. if (source[25] != ' ' || source[26] != 'G' || source[27] != 'M' || source[28] != 'T')
  4485. {
  4486. result.SetBadDateTimeFailure();
  4487. return false;
  4488. }
  4489. // Validate that the parsed date is valid according to the calendar.
  4490. if (!parseInfo.calendar.TryToDateTime(year, month, day, hour, minute, second, 0, 0, out result.parsedDate))
  4491. {
  4492. result.SetFailure(ParseFailureKind.FormatBadDateTimeCalendar, nameof(SR.Format_BadDateTimeCalendar));
  4493. return false;
  4494. }
  4495. // And validate that the parsed day of week matches what the calendar said it should be.
  4496. if (dayOfWeek != result.parsedDate.DayOfWeek)
  4497. {
  4498. result.SetFailure(ParseFailureKind.FormatWithOriginalDateTime, nameof(SR.Format_BadDayOfWeek));
  4499. return false;
  4500. }
  4501. return true;
  4502. }
  4503. private static bool ParseFormatO(ReadOnlySpan<char> source, ref ParsingInfo parseInfo, ref DateTimeResult result)
  4504. {
  4505. // Examples:
  4506. // 2017-06-12T05:30:45.7680000 (interpreted as local time wrt to current time zone)
  4507. // 2017-06-12T05:30:45.7680000Z (Z is short for "+00:00" but also distinguishes DateTimeKind.Utc from DateTimeKind.Local)
  4508. // 2017-06-12T05:30:45.7680000-7:00 (special-case of one-digit offset hour)
  4509. // 2017-06-12T05:30:45.7680000-07:00
  4510. if ((uint)source.Length < 27 ||
  4511. source[4] != '-' ||
  4512. source[7] != '-' ||
  4513. source[10] != 'T' ||
  4514. source[13] != ':' ||
  4515. source[16] != ':' ||
  4516. source[19] != '.')
  4517. {
  4518. result.SetBadDateTimeFailure();
  4519. return false;
  4520. }
  4521. int year;
  4522. {
  4523. uint y1 = (uint)(source[0] - '0'), y2 = (uint)(source[1] - '0'), y3 = (uint)(source[2] - '0'), y4 = (uint)(source[3] - '0');
  4524. if (y1 > 9 || y2 > 9 || y3 > 9 || y4 > 9)
  4525. {
  4526. result.SetBadDateTimeFailure();
  4527. return false;
  4528. }
  4529. year = (int)(y1*1000 + y2*100 + y3*10 + y4);
  4530. }
  4531. int month;
  4532. {
  4533. uint m1 = (uint)(source[5] - '0'), m2 = (uint)(source[6] - '0');
  4534. if (m1 > 9 || m2 > 9)
  4535. {
  4536. result.SetBadDateTimeFailure();
  4537. return false;
  4538. }
  4539. month = (int)(m1*10 + m2);
  4540. }
  4541. int day;
  4542. {
  4543. uint d1 = (uint)(source[8] - '0'), d2 = (uint)(source[9] - '0');
  4544. if (d1 > 9 || d2 > 9)
  4545. {
  4546. result.SetBadDateTimeFailure();
  4547. return false;
  4548. }
  4549. day = (int)(d1*10 + d2);
  4550. }
  4551. int hour;
  4552. {
  4553. uint h1 = (uint)(source[11] - '0'), h2 = (uint)(source[12] - '0');
  4554. if (h1 > 9 || h2 > 9)
  4555. {
  4556. result.SetBadDateTimeFailure();
  4557. return false;
  4558. }
  4559. hour = (int)(h1*10 + h2);
  4560. }
  4561. int minute;
  4562. {
  4563. uint m1 = (uint)(source[14] - '0'), m2 = (uint)(source[15] - '0');
  4564. if (m1 > 9 || m2 > 9)
  4565. {
  4566. result.SetBadDateTimeFailure();
  4567. return false;
  4568. }
  4569. minute = (int)(m1*10 + m2);
  4570. }
  4571. int second;
  4572. {
  4573. uint s1 = (uint)(source[17] - '0'), s2 = (uint)(source[18] - '0');
  4574. if (s1 > 9 || s2 > 9)
  4575. {
  4576. result.SetBadDateTimeFailure();
  4577. return false;
  4578. }
  4579. second = (int)(s1*10 + s2);
  4580. }
  4581. double fraction;
  4582. {
  4583. uint f1 = (uint)(source[20] - '0');
  4584. uint f2 = (uint)(source[21] - '0');
  4585. uint f3 = (uint)(source[22] - '0');
  4586. uint f4 = (uint)(source[23] - '0');
  4587. uint f5 = (uint)(source[24] - '0');
  4588. uint f6 = (uint)(source[25] - '0');
  4589. uint f7 = (uint)(source[26] - '0');
  4590. if (f1 > 9 || f2 > 9 || f3 > 9 || f4 > 9 || f5 > 9 || f6 > 9 || f7 > 9)
  4591. {
  4592. result.SetBadDateTimeFailure();
  4593. return false;
  4594. }
  4595. fraction = (f1*1000000 + f2*100000 + f3*10000 + f4*1000 + f5*100 + f6*10 + f7) / 10000000.0;
  4596. }
  4597. if (!DateTime.TryCreate(year, month, day, hour, minute, second, 0, out DateTime dateTime))
  4598. {
  4599. result.SetBadDateTimeFailure();
  4600. return false;
  4601. }
  4602. if (!dateTime.TryAddTicks((long)Math.Round(fraction * Calendar.TicksPerSecond), out result.parsedDate))
  4603. {
  4604. result.SetBadDateTimeFailure();
  4605. return false;
  4606. }
  4607. if ((uint)source.Length > 27)
  4608. {
  4609. char offsetChar = source[27];
  4610. switch (offsetChar)
  4611. {
  4612. case 'Z':
  4613. if (source.Length != 28)
  4614. {
  4615. result.SetBadDateTimeFailure();
  4616. return false;
  4617. }
  4618. result.flags |= ParseFlags.TimeZoneUsed | ParseFlags.TimeZoneUtc;
  4619. break;
  4620. case '+':
  4621. case '-':
  4622. int offsetHours, colonIndex;
  4623. if ((uint)source.Length == 33)
  4624. {
  4625. uint oh1 = (uint)(source[28] - '0'), oh2 = (uint)(source[29] - '0');
  4626. if (oh1 > 9 || oh2 > 9)
  4627. {
  4628. result.SetBadDateTimeFailure();
  4629. return false;
  4630. }
  4631. offsetHours = (int)(oh1 * 10 + oh2);
  4632. colonIndex = 30;
  4633. }
  4634. else if ((uint)source.Length == 32) // special-case allowed for compat: only one offset hour digit
  4635. {
  4636. offsetHours = source[28] - '0';
  4637. if ((uint)offsetHours > 9)
  4638. {
  4639. result.SetBadDateTimeFailure();
  4640. return false;
  4641. }
  4642. colonIndex = 29;
  4643. }
  4644. else
  4645. {
  4646. result.SetBadDateTimeFailure();
  4647. return false;
  4648. }
  4649. if (source[colonIndex] != ':')
  4650. {
  4651. result.SetBadDateTimeFailure();
  4652. return false;
  4653. }
  4654. int offsetMinutes;
  4655. {
  4656. uint om1 = (uint)(source[colonIndex + 1] - '0'), om2 = (uint)(source[colonIndex + 2] - '0');
  4657. if (om1 > 9 || om2 > 9)
  4658. {
  4659. result.SetBadDateTimeFailure();
  4660. return false;
  4661. }
  4662. offsetMinutes = (int)(om1*10 + om2);
  4663. }
  4664. result.flags |= ParseFlags.TimeZoneUsed;
  4665. result.timeZoneOffset = new TimeSpan(offsetHours, offsetMinutes, 0);
  4666. if (offsetChar == '-')
  4667. {
  4668. result.timeZoneOffset = result.timeZoneOffset.Negate();
  4669. }
  4670. break;
  4671. default:
  4672. result.SetBadDateTimeFailure();
  4673. return false;
  4674. }
  4675. }
  4676. return DetermineTimeZoneAdjustments(ref result, DateTimeStyles.None, bTimeOnly: false);
  4677. }
  4678. private static Exception GetDateTimeParseException(ref DateTimeResult result)
  4679. {
  4680. switch (result.failure)
  4681. {
  4682. case ParseFailureKind.ArgumentNull:
  4683. return new ArgumentNullException(result.failureArgumentName, SR.GetResourceString(result.failureMessageID));
  4684. case ParseFailureKind.Format:
  4685. return new FormatException(SR.GetResourceString(result.failureMessageID));
  4686. case ParseFailureKind.FormatWithParameter:
  4687. return new FormatException(SR.Format(SR.GetResourceString(result.failureMessageID), result.failureMessageFormatArgument));
  4688. case ParseFailureKind.FormatBadDateTimeCalendar:
  4689. return new FormatException(SR.Format(SR.GetResourceString(result.failureMessageID), new string(result.originalDateTimeString), result.calendar));
  4690. case ParseFailureKind.FormatWithOriginalDateTime:
  4691. return new FormatException(SR.Format(SR.GetResourceString(result.failureMessageID), new string(result.originalDateTimeString)));
  4692. case ParseFailureKind.FormatWithFormatSpecifier:
  4693. return new FormatException(SR.Format(SR.GetResourceString(result.failureMessageID), new string(result.failedFormatSpecifier)));
  4694. case ParseFailureKind.FormatWithOriginalDateTimeAndParameter:
  4695. return new FormatException(SR.Format(SR.GetResourceString(result.failureMessageID), new string(result.originalDateTimeString), result.failureMessageFormatArgument));
  4696. default:
  4697. Debug.Fail("Unknown DateTimeParseFailure: " + result.failure.ToString());
  4698. return null;
  4699. }
  4700. }
  4701. [Conditional("_LOGGING")]
  4702. private static void LexTraceExit(string message, DS dps)
  4703. {
  4704. #if _LOGGING
  4705. if (!_tracingEnabled)
  4706. return;
  4707. Trace($"Lex return {message}, DS.{dps}");
  4708. #endif // _LOGGING
  4709. }
  4710. [Conditional("_LOGGING")]
  4711. private static void PTSTraceExit(DS dps, bool passed)
  4712. {
  4713. #if _LOGGING
  4714. if (!_tracingEnabled)
  4715. return;
  4716. Trace($"ProcessTerminalState {(passed ? "passed" : "failed")} @ DS.{dps}");
  4717. #endif // _LOGGING
  4718. }
  4719. [Conditional("_LOGGING")]
  4720. private static void TPTraceExit(string message, DS dps)
  4721. {
  4722. #if _LOGGING
  4723. if (!_tracingEnabled)
  4724. return;
  4725. Trace($"TryParse return {message}, DS.{dps}");
  4726. #endif // _LOGGING
  4727. }
  4728. [Conditional("_LOGGING")]
  4729. private static void DTFITrace(DateTimeFormatInfo dtfi)
  4730. {
  4731. #if _LOGGING
  4732. if (!_tracingEnabled)
  4733. return;
  4734. Trace("DateTimeFormatInfo Properties");
  4735. Trace($" NativeCalendarName {Hex(dtfi.NativeCalendarName)}");
  4736. Trace($" AMDesignator {Hex(dtfi.AMDesignator)}");
  4737. Trace($" PMDesignator {Hex(dtfi.PMDesignator)}");
  4738. Trace($" TimeSeparator {Hex(dtfi.TimeSeparator)}");
  4739. Trace($" AbbrvDayNames {Hex(dtfi.AbbreviatedDayNames)}");
  4740. Trace($" ShortestDayNames {Hex(dtfi.ShortestDayNames)}");
  4741. Trace($" DayNames {Hex(dtfi.DayNames)}");
  4742. Trace($" AbbrvMonthNames {Hex(dtfi.AbbreviatedMonthNames)}");
  4743. Trace($" MonthNames {Hex(dtfi.MonthNames)}");
  4744. Trace($" AbbrvMonthGenNames {Hex(dtfi.AbbreviatedMonthGenitiveNames)}");
  4745. Trace($" MonthGenNames {Hex(dtfi.MonthGenitiveNames)}");
  4746. #endif // _LOGGING
  4747. }
  4748. #if _LOGGING
  4749. // return a string in the form: "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
  4750. private static string Hex(string[] strs)
  4751. {
  4752. if (strs == null || strs.Length == 0)
  4753. return string.Empty;
  4754. if (strs.Length == 1)
  4755. return Hex(strs[0]);
  4756. int curLineLength = 0;
  4757. int maxLineLength = 55;
  4758. int newLinePadding = 20;
  4759. //invariant: strs.Length >= 2
  4760. StringBuilder buffer = new StringBuilder();
  4761. buffer.Append(Hex(strs[0]));
  4762. curLineLength = buffer.Length;
  4763. string s;
  4764. for (int i = 1; i < strs.Length - 1; i++)
  4765. {
  4766. s = Hex(strs[i]);
  4767. if (s.Length > maxLineLength || (curLineLength + s.Length + 2) > maxLineLength)
  4768. {
  4769. buffer.Append(',');
  4770. buffer.Append(Environment.NewLine);
  4771. buffer.Append(' ', newLinePadding);
  4772. curLineLength = 0;
  4773. }
  4774. else
  4775. {
  4776. buffer.Append(", ");
  4777. curLineLength += 2;
  4778. }
  4779. buffer.Append(s);
  4780. curLineLength += s.Length;
  4781. }
  4782. buffer.Append(',');
  4783. s = Hex(strs[strs.Length - 1]);
  4784. if (s.Length > maxLineLength || (curLineLength + s.Length + 6) > maxLineLength)
  4785. {
  4786. buffer.Append(Environment.NewLine);
  4787. buffer.Append(' ', newLinePadding);
  4788. }
  4789. else
  4790. {
  4791. buffer.Append(' ');
  4792. }
  4793. buffer.Append(s);
  4794. return buffer.ToString();
  4795. }
  4796. // return a string in the form: "Sun"
  4797. private static string Hex(string str) => Hex((ReadOnlySpan<char>)str);
  4798. private static string Hex(ReadOnlySpan<char> str)
  4799. {
  4800. StringBuilder buffer = new StringBuilder();
  4801. buffer.Append("\"");
  4802. for (int i = 0; i < str.Length; i++)
  4803. {
  4804. if (str[i] <= '\x007f')
  4805. buffer.Append(str[i]);
  4806. else
  4807. buffer.Append("\\u" + ((int)str[i]).ToString("x4", CultureInfo.InvariantCulture));
  4808. }
  4809. buffer.Append("\"");
  4810. return buffer.ToString();
  4811. }
  4812. // return an unicode escaped string form of char c
  4813. private static string Hex(char c)
  4814. {
  4815. if (c <= '\x007f')
  4816. return c.ToString(CultureInfo.InvariantCulture);
  4817. else
  4818. return "\\u" + ((int)c).ToString("x4", CultureInfo.InvariantCulture);
  4819. }
  4820. private static void Trace(string s)
  4821. {
  4822. // Internal.Console.WriteLine(s);
  4823. }
  4824. private static bool _tracingEnabled = false;
  4825. #endif // _LOGGING
  4826. }
  4827. //
  4828. // This is a string parsing helper which wraps a String object.
  4829. // It has a Index property which tracks
  4830. // the current parsing pointer of the string.
  4831. //
  4832. internal ref struct __DTString
  4833. {
  4834. //
  4835. // Value property: stores the real string to be parsed.
  4836. //
  4837. internal ReadOnlySpan<char> Value;
  4838. //
  4839. // Index property: points to the character that we are currently parsing.
  4840. //
  4841. internal int Index;
  4842. // The length of Value string.
  4843. internal int Length => Value.Length;
  4844. // The current character to be looked at.
  4845. internal char m_current;
  4846. private CompareInfo m_info;
  4847. // Flag to indicate if we encouter an digit, we should check for token or not.
  4848. // In some cultures, such as mn-MN, it uses "\x0031\x00a0\x0434\x04af\x0433\x044d\x044d\x0440\x00a0\x0441\x0430\x0440" in month names.
  4849. private bool m_checkDigitToken;
  4850. internal __DTString(ReadOnlySpan<char> str, DateTimeFormatInfo dtfi, bool checkDigitToken) : this(str, dtfi)
  4851. {
  4852. m_checkDigitToken = checkDigitToken;
  4853. }
  4854. internal __DTString(ReadOnlySpan<char> str, DateTimeFormatInfo dtfi)
  4855. {
  4856. Debug.Assert(dtfi != null, "Expected non-null DateTimeFormatInfo");
  4857. Index = -1;
  4858. Value = str;
  4859. m_current = '\0';
  4860. m_info = dtfi.CompareInfo;
  4861. m_checkDigitToken = ((dtfi.FormatFlags & DateTimeFormatFlags.UseDigitPrefixInTokens) != 0);
  4862. }
  4863. internal CompareInfo CompareInfo
  4864. {
  4865. get { return m_info; }
  4866. }
  4867. //
  4868. // Advance the Index.
  4869. // Return true if Index is NOT at the end of the string.
  4870. //
  4871. // Typical usage:
  4872. // while (str.GetNext())
  4873. // {
  4874. // char ch = str.GetChar()
  4875. // }
  4876. internal bool GetNext()
  4877. {
  4878. Index++;
  4879. if (Index < Length)
  4880. {
  4881. m_current = Value[Index];
  4882. return (true);
  4883. }
  4884. return (false);
  4885. }
  4886. internal bool AtEnd()
  4887. {
  4888. return Index < Length ? false : true;
  4889. }
  4890. internal bool Advance(int count)
  4891. {
  4892. Debug.Assert(Index + count <= Length, "__DTString::Advance: Index + count <= len");
  4893. Index += count;
  4894. if (Index < Length)
  4895. {
  4896. m_current = Value[Index];
  4897. return (true);
  4898. }
  4899. return (false);
  4900. }
  4901. // Used by DateTime.Parse() to get the next token.
  4902. internal void GetRegularToken(out TokenType tokenType, out int tokenValue, DateTimeFormatInfo dtfi)
  4903. {
  4904. tokenValue = 0;
  4905. if (Index >= Length)
  4906. {
  4907. tokenType = TokenType.EndOfString;
  4908. return;
  4909. }
  4910. tokenType = TokenType.UnknownToken;
  4911. Start:
  4912. if (DateTimeParse.IsDigit(m_current))
  4913. {
  4914. // This is a digit.
  4915. tokenValue = m_current - '0';
  4916. int value;
  4917. int start = Index;
  4918. //
  4919. // Collect other digits.
  4920. //
  4921. while (++Index < Length)
  4922. {
  4923. m_current = Value[Index];
  4924. value = m_current - '0';
  4925. if (value >= 0 && value <= 9)
  4926. {
  4927. tokenValue = tokenValue * 10 + value;
  4928. }
  4929. else
  4930. {
  4931. break;
  4932. }
  4933. }
  4934. if (Index - start > DateTimeParse.MaxDateTimeNumberDigits)
  4935. {
  4936. tokenType = TokenType.NumberToken;
  4937. tokenValue = -1;
  4938. }
  4939. else if (Index - start < 3)
  4940. {
  4941. tokenType = TokenType.NumberToken;
  4942. }
  4943. else
  4944. {
  4945. // If there are more than 3 digits, assume that it's a year value.
  4946. tokenType = TokenType.YearNumberToken;
  4947. }
  4948. if (m_checkDigitToken)
  4949. {
  4950. int save = Index;
  4951. char saveCh = m_current;
  4952. // Re-scan using the staring Index to see if this is a token.
  4953. Index = start; // To include the first digit.
  4954. m_current = Value[Index];
  4955. TokenType tempType;
  4956. int tempValue;
  4957. // This DTFI has tokens starting with digits.
  4958. // E.g. mn-MN has month name like "\x0031\x00a0\x0434\x04af\x0433\x044d\x044d\x0440\x00a0\x0441\x0430\x0440"
  4959. if (dtfi.Tokenize(TokenType.RegularTokenMask, out tempType, out tempValue, ref this))
  4960. {
  4961. tokenType = tempType;
  4962. tokenValue = tempValue;
  4963. // This is a token, so the Index has been advanced propertly in DTFI.Tokenizer().
  4964. }
  4965. else
  4966. {
  4967. // Use the number token value.
  4968. // Restore the index.
  4969. Index = save;
  4970. m_current = saveCh;
  4971. }
  4972. }
  4973. }
  4974. else if (char.IsWhiteSpace(m_current))
  4975. {
  4976. // Just skip to the next character.
  4977. while (++Index < Length)
  4978. {
  4979. m_current = Value[Index];
  4980. if (!(char.IsWhiteSpace(m_current)))
  4981. {
  4982. goto Start;
  4983. }
  4984. }
  4985. // We have reached the end of string.
  4986. tokenType = TokenType.EndOfString;
  4987. }
  4988. else
  4989. {
  4990. dtfi.Tokenize(TokenType.RegularTokenMask, out tokenType, out tokenValue, ref this);
  4991. }
  4992. }
  4993. internal TokenType GetSeparatorToken(DateTimeFormatInfo dtfi, out int indexBeforeSeparator, out char charBeforeSeparator)
  4994. {
  4995. indexBeforeSeparator = Index;
  4996. charBeforeSeparator = m_current;
  4997. TokenType tokenType;
  4998. if (!SkipWhiteSpaceCurrent())
  4999. {
  5000. // Reach the end of the string.
  5001. return (TokenType.SEP_End);
  5002. }
  5003. if (!DateTimeParse.IsDigit(m_current))
  5004. {
  5005. // Not a digit. Tokenize it.
  5006. int tokenValue;
  5007. bool found = dtfi.Tokenize(TokenType.SeparatorTokenMask, out tokenType, out tokenValue, ref this);
  5008. if (!found)
  5009. {
  5010. tokenType = TokenType.SEP_Space;
  5011. }
  5012. }
  5013. else
  5014. {
  5015. // Do nothing here. If we see a number, it will not be a separator. There is no need wasting time trying to find the
  5016. // separator token.
  5017. tokenType = TokenType.SEP_Space;
  5018. }
  5019. return (tokenType);
  5020. }
  5021. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  5022. internal bool MatchSpecifiedWord(string target) =>
  5023. Index + target.Length <= Length &&
  5024. m_info.Compare(Value.Slice(Index, target.Length), target, CompareOptions.IgnoreCase) == 0;
  5025. private static readonly char[] WhiteSpaceChecks = new char[] { ' ', '\u00A0' };
  5026. internal bool MatchSpecifiedWords(string target, bool checkWordBoundary, ref int matchLength)
  5027. {
  5028. int valueRemaining = Value.Length - Index;
  5029. matchLength = target.Length;
  5030. if (matchLength > valueRemaining || m_info.Compare(Value.Slice(Index, matchLength), target, CompareOptions.IgnoreCase) != 0)
  5031. {
  5032. // Check word by word
  5033. int targetPosition = 0; // Where we are in the target string
  5034. int thisPosition = Index; // Where we are in this string
  5035. int wsIndex = target.IndexOfAny(WhiteSpaceChecks, targetPosition);
  5036. if (wsIndex == -1)
  5037. {
  5038. return false;
  5039. }
  5040. do
  5041. {
  5042. int segmentLength = wsIndex - targetPosition;
  5043. if (thisPosition >= Value.Length - segmentLength)
  5044. { // Subtraction to prevent overflow.
  5045. return false;
  5046. }
  5047. if (segmentLength == 0)
  5048. {
  5049. // If segmentLength == 0, it means that we have leading space in the target string.
  5050. // In that case, skip the leading spaces in the target and this string.
  5051. matchLength--;
  5052. }
  5053. else
  5054. {
  5055. // Make sure we also have whitespace in the input string
  5056. if (!char.IsWhiteSpace(Value[thisPosition + segmentLength]))
  5057. {
  5058. return false;
  5059. }
  5060. if (m_info.CompareOptionIgnoreCase(Value.Slice(thisPosition, segmentLength), target.AsSpan(targetPosition, segmentLength)) != 0)
  5061. {
  5062. return false;
  5063. }
  5064. // Advance the input string
  5065. thisPosition = thisPosition + segmentLength + 1;
  5066. }
  5067. // Advance our target string
  5068. targetPosition = wsIndex + 1;
  5069. // Skip past multiple whitespace
  5070. while (thisPosition < Value.Length && char.IsWhiteSpace(Value[thisPosition]))
  5071. {
  5072. thisPosition++;
  5073. matchLength++;
  5074. }
  5075. } while ((wsIndex = target.IndexOfAny(WhiteSpaceChecks, targetPosition)) >= 0);
  5076. // now check the last segment;
  5077. if (targetPosition < target.Length)
  5078. {
  5079. int segmentLength = target.Length - targetPosition;
  5080. if (thisPosition > Value.Length - segmentLength)
  5081. {
  5082. return false;
  5083. }
  5084. if (m_info.CompareOptionIgnoreCase(Value.Slice(thisPosition, segmentLength), target.AsSpan(targetPosition, segmentLength)) != 0)
  5085. {
  5086. return false;
  5087. }
  5088. }
  5089. }
  5090. if (checkWordBoundary)
  5091. {
  5092. int nextCharIndex = Index + matchLength;
  5093. if (nextCharIndex < Value.Length)
  5094. {
  5095. if (char.IsLetter(Value[nextCharIndex]))
  5096. {
  5097. return (false);
  5098. }
  5099. }
  5100. }
  5101. return (true);
  5102. }
  5103. //
  5104. // Check to see if the string starting from Index is a prefix of
  5105. // str.
  5106. // If a match is found, true value is returned and Index is updated to the next character to be parsed.
  5107. // Otherwise, Index is unchanged.
  5108. //
  5109. internal bool Match(string str)
  5110. {
  5111. if (++Index >= Length)
  5112. {
  5113. return (false);
  5114. }
  5115. if (str.Length > (Value.Length - Index))
  5116. {
  5117. return false;
  5118. }
  5119. if (m_info.Compare(Value.Slice(Index, str.Length), str, CompareOptions.Ordinal) == 0)
  5120. {
  5121. // Update the Index to the end of the matching string.
  5122. // So the following GetNext()/Match() opeartion will get
  5123. // the next character to be parsed.
  5124. Index += (str.Length - 1);
  5125. return (true);
  5126. }
  5127. return (false);
  5128. }
  5129. internal bool Match(char ch)
  5130. {
  5131. if (++Index >= Length)
  5132. {
  5133. return (false);
  5134. }
  5135. if (Value[Index] == ch)
  5136. {
  5137. m_current = ch;
  5138. return (true);
  5139. }
  5140. Index--;
  5141. return (false);
  5142. }
  5143. //
  5144. // Actions: From the current position, try matching the longest word in the specified string array.
  5145. // E.g. words[] = {"AB", "ABC", "ABCD"}, if the current position points to a substring like "ABC DEF",
  5146. // MatchLongestWords(words, ref MaxMatchStrLen) will return 1 (the index), and maxMatchLen will be 3.
  5147. // Returns:
  5148. // The index that contains the longest word to match
  5149. // Arguments:
  5150. // words The string array that contains words to search.
  5151. // maxMatchStrLen [in/out] the initialized maximum length. This parameter can be used to
  5152. // find the longest match in two string arrays.
  5153. //
  5154. internal int MatchLongestWords(string[] words, ref int maxMatchStrLen)
  5155. {
  5156. int result = -1;
  5157. for (int i = 0; i < words.Length; i++)
  5158. {
  5159. string word = words[i];
  5160. int matchLength = word.Length;
  5161. if (MatchSpecifiedWords(word, false, ref matchLength))
  5162. {
  5163. if (matchLength > maxMatchStrLen)
  5164. {
  5165. maxMatchStrLen = matchLength;
  5166. result = i;
  5167. }
  5168. }
  5169. }
  5170. return (result);
  5171. }
  5172. //
  5173. // Get the number of repeat character after the current character.
  5174. // For a string "hh:mm:ss" at Index of 3. GetRepeatCount() = 2, and Index
  5175. // will point to the second ':'.
  5176. //
  5177. internal int GetRepeatCount()
  5178. {
  5179. char repeatChar = Value[Index];
  5180. int pos = Index + 1;
  5181. while ((pos < Length) && (Value[pos] == repeatChar))
  5182. {
  5183. pos++;
  5184. }
  5185. int repeatCount = (pos - Index);
  5186. // Update the Index to the end of the repeated characters.
  5187. // So the following GetNext() opeartion will get
  5188. // the next character to be parsed.
  5189. Index = pos - 1;
  5190. return (repeatCount);
  5191. }
  5192. // Return false when end of string is encountered or a non-digit character is found.
  5193. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  5194. internal bool GetNextDigit() =>
  5195. ++Index < Length &&
  5196. DateTimeParse.IsDigit(Value[Index]);
  5197. //
  5198. // Get the current character.
  5199. //
  5200. internal char GetChar()
  5201. {
  5202. Debug.Assert(Index >= 0 && Index < Length, "Index >= 0 && Index < len");
  5203. return (Value[Index]);
  5204. }
  5205. //
  5206. // Convert the current character to a digit, and return it.
  5207. //
  5208. internal int GetDigit()
  5209. {
  5210. Debug.Assert(Index >= 0 && Index < Length, "Index >= 0 && Index < len");
  5211. Debug.Assert(DateTimeParse.IsDigit(Value[Index]), "IsDigit(Value[Index])");
  5212. return (Value[Index] - '0');
  5213. }
  5214. //
  5215. // Eat White Space ahead of the current position
  5216. //
  5217. // Return false if end of string is encountered.
  5218. //
  5219. internal void SkipWhiteSpaces()
  5220. {
  5221. // Look ahead to see if the next character
  5222. // is a whitespace.
  5223. while (Index + 1 < Length)
  5224. {
  5225. char ch = Value[Index + 1];
  5226. if (!char.IsWhiteSpace(ch))
  5227. {
  5228. return;
  5229. }
  5230. Index++;
  5231. }
  5232. return;
  5233. }
  5234. //
  5235. // Skip white spaces from the current position
  5236. //
  5237. // Return false if end of string is encountered.
  5238. //
  5239. internal bool SkipWhiteSpaceCurrent()
  5240. {
  5241. if (Index >= Length)
  5242. {
  5243. return (false);
  5244. }
  5245. if (!char.IsWhiteSpace(m_current))
  5246. {
  5247. return (true);
  5248. }
  5249. while (++Index < Length)
  5250. {
  5251. m_current = Value[Index];
  5252. if (!char.IsWhiteSpace(m_current))
  5253. {
  5254. return (true);
  5255. }
  5256. // Nothing here.
  5257. }
  5258. return (false);
  5259. }
  5260. internal void TrimTail()
  5261. {
  5262. int i = Length - 1;
  5263. while (i >= 0 && char.IsWhiteSpace(Value[i]))
  5264. {
  5265. i--;
  5266. }
  5267. Value = Value.Slice(0, i + 1);
  5268. }
  5269. // Trim the trailing spaces within a quoted string.
  5270. // Call this after TrimTail() is done.
  5271. internal void RemoveTrailingInQuoteSpaces()
  5272. {
  5273. int i = Length - 1;
  5274. if (i <= 1)
  5275. {
  5276. return;
  5277. }
  5278. char ch = Value[i];
  5279. // Check if the last character is a quote.
  5280. if (ch == '\'' || ch == '\"')
  5281. {
  5282. if (char.IsWhiteSpace(Value[i - 1]))
  5283. {
  5284. i--;
  5285. while (i >= 1 && char.IsWhiteSpace(Value[i - 1]))
  5286. {
  5287. i--;
  5288. }
  5289. Span<char> result = new char[i + 1];
  5290. result[i] = ch;
  5291. Value.Slice(0, i).CopyTo(result);
  5292. Value = result;
  5293. }
  5294. }
  5295. }
  5296. // Trim the leading spaces within a quoted string.
  5297. // Call this after the leading spaces before quoted string are trimmed.
  5298. internal void RemoveLeadingInQuoteSpaces()
  5299. {
  5300. if (Length <= 2)
  5301. {
  5302. return;
  5303. }
  5304. int i = 0;
  5305. char ch = Value[i];
  5306. // Check if the last character is a quote.
  5307. if (ch == '\'' || ch == '\"')
  5308. {
  5309. while ((i + 1) < Length && char.IsWhiteSpace(Value[i + 1]))
  5310. {
  5311. i++;
  5312. }
  5313. if (i != 0)
  5314. {
  5315. Span<char> result = new char[Value.Length - i];
  5316. result[0] = ch;
  5317. Value.Slice(i + 1).CopyTo(result.Slice(1));
  5318. Value = result;
  5319. }
  5320. }
  5321. }
  5322. internal DTSubString GetSubString()
  5323. {
  5324. DTSubString sub = new DTSubString();
  5325. sub.index = Index;
  5326. sub.s = Value;
  5327. while (Index + sub.length < Length)
  5328. {
  5329. DTSubStringType currentType;
  5330. char ch = Value[Index + sub.length];
  5331. if (ch >= '0' && ch <= '9')
  5332. {
  5333. currentType = DTSubStringType.Number;
  5334. }
  5335. else
  5336. {
  5337. currentType = DTSubStringType.Other;
  5338. }
  5339. if (sub.length == 0)
  5340. {
  5341. sub.type = currentType;
  5342. }
  5343. else
  5344. {
  5345. if (sub.type != currentType)
  5346. {
  5347. break;
  5348. }
  5349. }
  5350. sub.length++;
  5351. if (currentType == DTSubStringType.Number)
  5352. {
  5353. // Incorporate the number into the value
  5354. // Limit the digits to prevent overflow
  5355. if (sub.length > DateTimeParse.MaxDateTimeNumberDigits)
  5356. {
  5357. sub.type = DTSubStringType.Invalid;
  5358. return sub;
  5359. }
  5360. int number = ch - '0';
  5361. Debug.Assert(number >= 0 && number <= 9, "number >= 0 && number <= 9");
  5362. sub.value = sub.value * 10 + number;
  5363. }
  5364. else
  5365. {
  5366. // For non numbers, just return this length 1 token. This should be expanded
  5367. // to more types of thing if this parsing approach is used for things other
  5368. // than numbers and single characters
  5369. break;
  5370. }
  5371. }
  5372. if (sub.length == 0)
  5373. {
  5374. sub.type = DTSubStringType.End;
  5375. return sub;
  5376. }
  5377. return sub;
  5378. }
  5379. internal void ConsumeSubString(DTSubString sub)
  5380. {
  5381. Debug.Assert(sub.index == Index, "sub.index == Index");
  5382. Debug.Assert(sub.index + sub.length <= Length, "sub.index + sub.length <= len");
  5383. Index = sub.index + sub.length;
  5384. if (Index < Length)
  5385. {
  5386. m_current = Value[Index];
  5387. }
  5388. }
  5389. }
  5390. internal enum DTSubStringType
  5391. {
  5392. Unknown = 0,
  5393. Invalid = 1,
  5394. Number = 2,
  5395. End = 3,
  5396. Other = 4,
  5397. }
  5398. internal ref struct DTSubString
  5399. {
  5400. internal ReadOnlySpan<char> s;
  5401. internal int index;
  5402. internal int length;
  5403. internal DTSubStringType type;
  5404. internal int value;
  5405. internal char this[int relativeIndex]
  5406. {
  5407. get
  5408. {
  5409. return s[index + relativeIndex];
  5410. }
  5411. }
  5412. }
  5413. //
  5414. // The buffer to store the parsing token.
  5415. //
  5416. internal
  5417. struct DateTimeToken
  5418. {
  5419. internal DateTimeParse.DTT dtt; // Store the token
  5420. internal TokenType suffix; // Store the CJK Year/Month/Day suffix (if any)
  5421. internal int num; // Store the number that we are parsing (if any)
  5422. }
  5423. //
  5424. // The buffer to store temporary parsing information.
  5425. //
  5426. internal
  5427. unsafe struct DateTimeRawInfo
  5428. {
  5429. private int* num;
  5430. internal int numCount;
  5431. internal int month;
  5432. internal int year;
  5433. internal int dayOfWeek;
  5434. internal int era;
  5435. internal DateTimeParse.TM timeMark;
  5436. internal double fraction;
  5437. internal bool hasSameDateAndTimeSeparators;
  5438. internal void Init(int* numberBuffer)
  5439. {
  5440. month = -1;
  5441. year = -1;
  5442. dayOfWeek = -1;
  5443. era = -1;
  5444. timeMark = DateTimeParse.TM.NotSet;
  5445. fraction = -1;
  5446. num = numberBuffer;
  5447. }
  5448. internal unsafe void AddNumber(int value)
  5449. {
  5450. num[numCount++] = value;
  5451. }
  5452. internal unsafe int GetNumber(int index)
  5453. {
  5454. return num[index];
  5455. }
  5456. }
  5457. internal enum ParseFailureKind
  5458. {
  5459. None = 0,
  5460. ArgumentNull = 1,
  5461. Format = 2,
  5462. FormatWithParameter = 3,
  5463. FormatWithOriginalDateTime = 4,
  5464. FormatWithFormatSpecifier = 5,
  5465. FormatWithOriginalDateTimeAndParameter = 6,
  5466. FormatBadDateTimeCalendar = 7, // FormatException when ArgumentOutOfRange is thrown by a Calendar.TryToDateTime().
  5467. };
  5468. [Flags]
  5469. internal enum ParseFlags
  5470. {
  5471. HaveYear = 0x00000001,
  5472. HaveMonth = 0x00000002,
  5473. HaveDay = 0x00000004,
  5474. HaveHour = 0x00000008,
  5475. HaveMinute = 0x00000010,
  5476. HaveSecond = 0x00000020,
  5477. HaveTime = 0x00000040,
  5478. HaveDate = 0x00000080,
  5479. TimeZoneUsed = 0x00000100,
  5480. TimeZoneUtc = 0x00000200,
  5481. ParsedMonthName = 0x00000400,
  5482. CaptureOffset = 0x00000800,
  5483. YearDefault = 0x00001000,
  5484. Rfc1123Pattern = 0x00002000,
  5485. UtcSortPattern = 0x00004000,
  5486. }
  5487. //
  5488. // This will store the result of the parsing. And it will be eventually
  5489. // used to construct a DateTime instance.
  5490. //
  5491. internal
  5492. ref struct DateTimeResult
  5493. {
  5494. internal int Year;
  5495. internal int Month;
  5496. internal int Day;
  5497. //
  5498. // Set time default to 00:00:00.
  5499. //
  5500. internal int Hour;
  5501. internal int Minute;
  5502. internal int Second;
  5503. internal double fraction;
  5504. internal int era;
  5505. internal ParseFlags flags;
  5506. internal TimeSpan timeZoneOffset;
  5507. internal Calendar calendar;
  5508. internal DateTime parsedDate;
  5509. internal ParseFailureKind failure;
  5510. internal string failureMessageID;
  5511. internal object failureMessageFormatArgument;
  5512. internal string failureArgumentName;
  5513. internal ReadOnlySpan<char> originalDateTimeString;
  5514. internal ReadOnlySpan<char> failedFormatSpecifier;
  5515. internal void Init(ReadOnlySpan<char> originalDateTimeString)
  5516. {
  5517. this.originalDateTimeString = originalDateTimeString;
  5518. Year = -1;
  5519. Month = -1;
  5520. Day = -1;
  5521. fraction = -1;
  5522. era = -1;
  5523. }
  5524. internal void SetDate(int year, int month, int day)
  5525. {
  5526. Year = year;
  5527. Month = month;
  5528. Day = day;
  5529. }
  5530. internal void SetBadFormatSpecifierFailure()
  5531. {
  5532. SetBadFormatSpecifierFailure(ReadOnlySpan<char>.Empty);
  5533. }
  5534. internal void SetBadFormatSpecifierFailure(ReadOnlySpan<char> failedFormatSpecifier)
  5535. {
  5536. this.failure = ParseFailureKind.FormatWithFormatSpecifier;
  5537. this.failureMessageID = nameof(SR.Format_BadFormatSpecifier);
  5538. this.failedFormatSpecifier = failedFormatSpecifier;
  5539. }
  5540. internal void SetBadDateTimeFailure()
  5541. {
  5542. this.failure = ParseFailureKind.FormatWithOriginalDateTime;
  5543. this.failureMessageID = nameof(SR.Format_BadDateTime);
  5544. this.failureMessageFormatArgument = null;
  5545. }
  5546. internal void SetFailure(ParseFailureKind failure, string failureMessageID)
  5547. {
  5548. this.failure = failure;
  5549. this.failureMessageID = failureMessageID;
  5550. this.failureMessageFormatArgument = null;
  5551. }
  5552. internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument)
  5553. {
  5554. this.failure = failure;
  5555. this.failureMessageID = failureMessageID;
  5556. this.failureMessageFormatArgument = failureMessageFormatArgument;
  5557. }
  5558. internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument, string failureArgumentName)
  5559. {
  5560. this.failure = failure;
  5561. this.failureMessageID = failureMessageID;
  5562. this.failureMessageFormatArgument = failureMessageFormatArgument;
  5563. this.failureArgumentName = failureArgumentName;
  5564. }
  5565. }
  5566. // This is the helper data structure used in ParseExact().
  5567. internal struct ParsingInfo
  5568. {
  5569. internal Calendar calendar;
  5570. internal int dayOfWeek;
  5571. internal DateTimeParse.TM timeMark;
  5572. internal bool fUseHour12;
  5573. internal bool fUseTwoDigitYear;
  5574. internal bool fAllowInnerWhite;
  5575. internal bool fAllowTrailingWhite;
  5576. internal bool fCustomNumberParser;
  5577. internal DateTimeParse.MatchNumberDelegate parseNumberDelegate;
  5578. internal void Init()
  5579. {
  5580. dayOfWeek = -1;
  5581. timeMark = DateTimeParse.TM.NotSet;
  5582. }
  5583. }
  5584. //
  5585. // The type of token that will be returned by DateTimeFormatInfo.Tokenize().
  5586. //
  5587. internal enum TokenType
  5588. {
  5589. // The valid token should start from 1.
  5590. // Regular tokens. The range is from 0x00 ~ 0xff.
  5591. NumberToken = 1, // The number. E.g. "12"
  5592. YearNumberToken = 2, // The number which is considered as year number, which has 3 or more digits. E.g. "2003"
  5593. Am = 3, // AM timemark. E.g. "AM"
  5594. Pm = 4, // PM timemark. E.g. "PM"
  5595. MonthToken = 5, // A word (or words) that represents a month name. E.g. "March"
  5596. EndOfString = 6, // End of string
  5597. DayOfWeekToken = 7, // A word (or words) that represents a day of week name. E.g. "Monday" or "Mon"
  5598. TimeZoneToken = 8, // A word that represents a timezone name. E.g. "GMT"
  5599. EraToken = 9, // A word that represents a era name. E.g. "A.D."
  5600. DateWordToken = 10, // A word that can appear in a DateTime string, but serves no parsing semantics. E.g. "de" in Spanish culture.
  5601. UnknownToken = 11, // An unknown word, which signals an error in parsing.
  5602. HebrewNumber = 12, // A number that is composed of Hebrew text. Hebrew calendar uses Hebrew digits for year values, month values, and day values.
  5603. JapaneseEraToken = 13, // Era name for JapaneseCalendar
  5604. TEraToken = 14, // Era name for TaiwanCalendar
  5605. IgnorableSymbol = 15, // A separator like "," that is equivalent to whitespace
  5606. // Separator tokens.
  5607. SEP_Unk = 0x100, // Unknown separator.
  5608. SEP_End = 0x200, // The end of the parsing string.
  5609. SEP_Space = 0x300, // Whitespace (including comma).
  5610. SEP_Am = 0x400, // AM timemark. E.g. "AM"
  5611. SEP_Pm = 0x500, // PM timemark. E.g. "PM"
  5612. SEP_Date = 0x600, // date separator. E.g. "/"
  5613. SEP_Time = 0x700, // time separator. E.g. ":"
  5614. SEP_YearSuff = 0x800, // Chinese/Japanese/Korean year suffix.
  5615. SEP_MonthSuff = 0x900, // Chinese/Japanese/Korean month suffix.
  5616. SEP_DaySuff = 0xa00, // Chinese/Japanese/Korean day suffix.
  5617. SEP_HourSuff = 0xb00, // Chinese/Japanese/Korean hour suffix.
  5618. SEP_MinuteSuff = 0xc00, // Chinese/Japanese/Korean minute suffix.
  5619. SEP_SecondSuff = 0xd00, // Chinese/Japanese/Korean second suffix.
  5620. SEP_LocalTimeMark = 0xe00, // 'T', used in ISO 8601 format.
  5621. SEP_DateOrOffset = 0xf00, // '-' which could be a date separator or start of a time zone offset
  5622. RegularTokenMask = 0x00ff,
  5623. SeparatorTokenMask = 0xff00,
  5624. }
  5625. }