DateTimeParse.cs 248 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131
  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. #if !FEATURE_COREFX_GLOBALIZATION
  4736. Trace($" NativeCalendarName {Hex(dtfi.NativeCalendarName)}");
  4737. #endif
  4738. Trace($" AMDesignator {Hex(dtfi.AMDesignator)}");
  4739. Trace($" PMDesignator {Hex(dtfi.PMDesignator)}");
  4740. Trace($" TimeSeparator {Hex(dtfi.TimeSeparator)}");
  4741. Trace($" AbbrvDayNames {Hex(dtfi.AbbreviatedDayNames)}");
  4742. Trace($" ShortestDayNames {Hex(dtfi.ShortestDayNames)}");
  4743. Trace($" DayNames {Hex(dtfi.DayNames)}");
  4744. Trace($" AbbrvMonthNames {Hex(dtfi.AbbreviatedMonthNames)}");
  4745. Trace($" MonthNames {Hex(dtfi.MonthNames)}");
  4746. Trace($" AbbrvMonthGenNames {Hex(dtfi.AbbreviatedMonthGenitiveNames)}");
  4747. Trace($" MonthGenNames {Hex(dtfi.MonthGenitiveNames)}");
  4748. #endif // _LOGGING
  4749. }
  4750. #if _LOGGING
  4751. // return a string in the form: "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
  4752. private static string Hex(string[] strs)
  4753. {
  4754. if (strs == null || strs.Length == 0)
  4755. return string.Empty;
  4756. if (strs.Length == 1)
  4757. return Hex(strs[0]);
  4758. int curLineLength = 0;
  4759. int maxLineLength = 55;
  4760. int newLinePadding = 20;
  4761. //invariant: strs.Length >= 2
  4762. StringBuilder buffer = new StringBuilder();
  4763. buffer.Append(Hex(strs[0]));
  4764. curLineLength = buffer.Length;
  4765. string s;
  4766. for (int i = 1; i < strs.Length - 1; i++)
  4767. {
  4768. s = Hex(strs[i]);
  4769. if (s.Length > maxLineLength || (curLineLength + s.Length + 2) > maxLineLength)
  4770. {
  4771. buffer.Append(',');
  4772. buffer.Append(Environment.NewLine);
  4773. buffer.Append(' ', newLinePadding);
  4774. curLineLength = 0;
  4775. }
  4776. else
  4777. {
  4778. buffer.Append(", ");
  4779. curLineLength += 2;
  4780. }
  4781. buffer.Append(s);
  4782. curLineLength += s.Length;
  4783. }
  4784. buffer.Append(',');
  4785. s = Hex(strs[strs.Length - 1]);
  4786. if (s.Length > maxLineLength || (curLineLength + s.Length + 6) > maxLineLength)
  4787. {
  4788. buffer.Append(Environment.NewLine);
  4789. buffer.Append(' ', newLinePadding);
  4790. }
  4791. else
  4792. {
  4793. buffer.Append(' ');
  4794. }
  4795. buffer.Append(s);
  4796. return buffer.ToString();
  4797. }
  4798. // return a string in the form: "Sun"
  4799. private static string Hex(string str) => Hex((ReadOnlySpan<char>)str);
  4800. private static string Hex(ReadOnlySpan<char> str)
  4801. {
  4802. StringBuilder buffer = new StringBuilder();
  4803. buffer.Append("\"");
  4804. for (int i = 0; i < str.Length; i++)
  4805. {
  4806. if (str[i] <= '\x007f')
  4807. buffer.Append(str[i]);
  4808. else
  4809. buffer.Append("\\u" + ((int)str[i]).ToString("x4", CultureInfo.InvariantCulture));
  4810. }
  4811. buffer.Append("\"");
  4812. return buffer.ToString();
  4813. }
  4814. // return an unicode escaped string form of char c
  4815. private static string Hex(char c)
  4816. {
  4817. if (c <= '\x007f')
  4818. return c.ToString(CultureInfo.InvariantCulture);
  4819. else
  4820. return "\\u" + ((int)c).ToString("x4", CultureInfo.InvariantCulture);
  4821. }
  4822. private static void Trace(string s)
  4823. {
  4824. // Internal.Console.WriteLine(s);
  4825. }
  4826. private static bool _tracingEnabled = false;
  4827. #endif // _LOGGING
  4828. }
  4829. //
  4830. // This is a string parsing helper which wraps a String object.
  4831. // It has a Index property which tracks
  4832. // the current parsing pointer of the string.
  4833. //
  4834. internal ref struct __DTString
  4835. {
  4836. //
  4837. // Value property: stores the real string to be parsed.
  4838. //
  4839. internal ReadOnlySpan<char> Value;
  4840. //
  4841. // Index property: points to the character that we are currently parsing.
  4842. //
  4843. internal int Index;
  4844. // The length of Value string.
  4845. internal int Length => Value.Length;
  4846. // The current character to be looked at.
  4847. internal char m_current;
  4848. private CompareInfo m_info;
  4849. // Flag to indicate if we encouter an digit, we should check for token or not.
  4850. // In some cultures, such as mn-MN, it uses "\x0031\x00a0\x0434\x04af\x0433\x044d\x044d\x0440\x00a0\x0441\x0430\x0440" in month names.
  4851. private bool m_checkDigitToken;
  4852. internal __DTString(ReadOnlySpan<char> str, DateTimeFormatInfo dtfi, bool checkDigitToken) : this(str, dtfi)
  4853. {
  4854. m_checkDigitToken = checkDigitToken;
  4855. }
  4856. internal __DTString(ReadOnlySpan<char> str, DateTimeFormatInfo dtfi)
  4857. {
  4858. Debug.Assert(dtfi != null, "Expected non-null DateTimeFormatInfo");
  4859. Index = -1;
  4860. Value = str;
  4861. m_current = '\0';
  4862. m_info = dtfi.CompareInfo;
  4863. m_checkDigitToken = ((dtfi.FormatFlags & DateTimeFormatFlags.UseDigitPrefixInTokens) != 0);
  4864. }
  4865. internal CompareInfo CompareInfo
  4866. {
  4867. get { return m_info; }
  4868. }
  4869. //
  4870. // Advance the Index.
  4871. // Return true if Index is NOT at the end of the string.
  4872. //
  4873. // Typical usage:
  4874. // while (str.GetNext())
  4875. // {
  4876. // char ch = str.GetChar()
  4877. // }
  4878. internal bool GetNext()
  4879. {
  4880. Index++;
  4881. if (Index < Length)
  4882. {
  4883. m_current = Value[Index];
  4884. return (true);
  4885. }
  4886. return (false);
  4887. }
  4888. internal bool AtEnd()
  4889. {
  4890. return Index < Length ? false : true;
  4891. }
  4892. internal bool Advance(int count)
  4893. {
  4894. Debug.Assert(Index + count <= Length, "__DTString::Advance: Index + count <= len");
  4895. Index += count;
  4896. if (Index < Length)
  4897. {
  4898. m_current = Value[Index];
  4899. return (true);
  4900. }
  4901. return (false);
  4902. }
  4903. // Used by DateTime.Parse() to get the next token.
  4904. internal void GetRegularToken(out TokenType tokenType, out int tokenValue, DateTimeFormatInfo dtfi)
  4905. {
  4906. tokenValue = 0;
  4907. if (Index >= Length)
  4908. {
  4909. tokenType = TokenType.EndOfString;
  4910. return;
  4911. }
  4912. tokenType = TokenType.UnknownToken;
  4913. Start:
  4914. if (DateTimeParse.IsDigit(m_current))
  4915. {
  4916. // This is a digit.
  4917. tokenValue = m_current - '0';
  4918. int value;
  4919. int start = Index;
  4920. //
  4921. // Collect other digits.
  4922. //
  4923. while (++Index < Length)
  4924. {
  4925. m_current = Value[Index];
  4926. value = m_current - '0';
  4927. if (value >= 0 && value <= 9)
  4928. {
  4929. tokenValue = tokenValue * 10 + value;
  4930. }
  4931. else
  4932. {
  4933. break;
  4934. }
  4935. }
  4936. if (Index - start > DateTimeParse.MaxDateTimeNumberDigits)
  4937. {
  4938. tokenType = TokenType.NumberToken;
  4939. tokenValue = -1;
  4940. }
  4941. else if (Index - start < 3)
  4942. {
  4943. tokenType = TokenType.NumberToken;
  4944. }
  4945. else
  4946. {
  4947. // If there are more than 3 digits, assume that it's a year value.
  4948. tokenType = TokenType.YearNumberToken;
  4949. }
  4950. if (m_checkDigitToken)
  4951. {
  4952. int save = Index;
  4953. char saveCh = m_current;
  4954. // Re-scan using the staring Index to see if this is a token.
  4955. Index = start; // To include the first digit.
  4956. m_current = Value[Index];
  4957. TokenType tempType;
  4958. int tempValue;
  4959. // This DTFI has tokens starting with digits.
  4960. // E.g. mn-MN has month name like "\x0031\x00a0\x0434\x04af\x0433\x044d\x044d\x0440\x00a0\x0441\x0430\x0440"
  4961. if (dtfi.Tokenize(TokenType.RegularTokenMask, out tempType, out tempValue, ref this))
  4962. {
  4963. tokenType = tempType;
  4964. tokenValue = tempValue;
  4965. // This is a token, so the Index has been advanced propertly in DTFI.Tokenizer().
  4966. }
  4967. else
  4968. {
  4969. // Use the number token value.
  4970. // Restore the index.
  4971. Index = save;
  4972. m_current = saveCh;
  4973. }
  4974. }
  4975. }
  4976. else if (char.IsWhiteSpace(m_current))
  4977. {
  4978. // Just skip to the next character.
  4979. while (++Index < Length)
  4980. {
  4981. m_current = Value[Index];
  4982. if (!(char.IsWhiteSpace(m_current)))
  4983. {
  4984. goto Start;
  4985. }
  4986. }
  4987. // We have reached the end of string.
  4988. tokenType = TokenType.EndOfString;
  4989. }
  4990. else
  4991. {
  4992. dtfi.Tokenize(TokenType.RegularTokenMask, out tokenType, out tokenValue, ref this);
  4993. }
  4994. }
  4995. internal TokenType GetSeparatorToken(DateTimeFormatInfo dtfi, out int indexBeforeSeparator, out char charBeforeSeparator)
  4996. {
  4997. indexBeforeSeparator = Index;
  4998. charBeforeSeparator = m_current;
  4999. TokenType tokenType;
  5000. if (!SkipWhiteSpaceCurrent())
  5001. {
  5002. // Reach the end of the string.
  5003. return (TokenType.SEP_End);
  5004. }
  5005. if (!DateTimeParse.IsDigit(m_current))
  5006. {
  5007. // Not a digit. Tokenize it.
  5008. int tokenValue;
  5009. bool found = dtfi.Tokenize(TokenType.SeparatorTokenMask, out tokenType, out tokenValue, ref this);
  5010. if (!found)
  5011. {
  5012. tokenType = TokenType.SEP_Space;
  5013. }
  5014. }
  5015. else
  5016. {
  5017. // Do nothing here. If we see a number, it will not be a separator. There is no need wasting time trying to find the
  5018. // separator token.
  5019. tokenType = TokenType.SEP_Space;
  5020. }
  5021. return (tokenType);
  5022. }
  5023. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  5024. internal bool MatchSpecifiedWord(string target) =>
  5025. Index + target.Length <= Length &&
  5026. m_info.Compare(Value.Slice(Index, target.Length), target, CompareOptions.IgnoreCase) == 0;
  5027. private static readonly char[] WhiteSpaceChecks = new char[] { ' ', '\u00A0' };
  5028. internal bool MatchSpecifiedWords(string target, bool checkWordBoundary, ref int matchLength)
  5029. {
  5030. int valueRemaining = Value.Length - Index;
  5031. matchLength = target.Length;
  5032. if (matchLength > valueRemaining || m_info.Compare(Value.Slice(Index, matchLength), target, CompareOptions.IgnoreCase) != 0)
  5033. {
  5034. // Check word by word
  5035. int targetPosition = 0; // Where we are in the target string
  5036. int thisPosition = Index; // Where we are in this string
  5037. int wsIndex = target.IndexOfAny(WhiteSpaceChecks, targetPosition);
  5038. if (wsIndex == -1)
  5039. {
  5040. return false;
  5041. }
  5042. do
  5043. {
  5044. int segmentLength = wsIndex - targetPosition;
  5045. if (thisPosition >= Value.Length - segmentLength)
  5046. { // Subtraction to prevent overflow.
  5047. return false;
  5048. }
  5049. if (segmentLength == 0)
  5050. {
  5051. // If segmentLength == 0, it means that we have leading space in the target string.
  5052. // In that case, skip the leading spaces in the target and this string.
  5053. matchLength--;
  5054. }
  5055. else
  5056. {
  5057. // Make sure we also have whitespace in the input string
  5058. if (!char.IsWhiteSpace(Value[thisPosition + segmentLength]))
  5059. {
  5060. return false;
  5061. }
  5062. if (m_info.CompareOptionIgnoreCase(Value.Slice(thisPosition, segmentLength), target.AsSpan(targetPosition, segmentLength)) != 0)
  5063. {
  5064. return false;
  5065. }
  5066. // Advance the input string
  5067. thisPosition = thisPosition + segmentLength + 1;
  5068. }
  5069. // Advance our target string
  5070. targetPosition = wsIndex + 1;
  5071. // Skip past multiple whitespace
  5072. while (thisPosition < Value.Length && char.IsWhiteSpace(Value[thisPosition]))
  5073. {
  5074. thisPosition++;
  5075. matchLength++;
  5076. }
  5077. } while ((wsIndex = target.IndexOfAny(WhiteSpaceChecks, targetPosition)) >= 0);
  5078. // now check the last segment;
  5079. if (targetPosition < target.Length)
  5080. {
  5081. int segmentLength = target.Length - targetPosition;
  5082. if (thisPosition > Value.Length - segmentLength)
  5083. {
  5084. return false;
  5085. }
  5086. if (m_info.CompareOptionIgnoreCase(Value.Slice(thisPosition, segmentLength), target.AsSpan(targetPosition, segmentLength)) != 0)
  5087. {
  5088. return false;
  5089. }
  5090. }
  5091. }
  5092. if (checkWordBoundary)
  5093. {
  5094. int nextCharIndex = Index + matchLength;
  5095. if (nextCharIndex < Value.Length)
  5096. {
  5097. if (char.IsLetter(Value[nextCharIndex]))
  5098. {
  5099. return (false);
  5100. }
  5101. }
  5102. }
  5103. return (true);
  5104. }
  5105. //
  5106. // Check to see if the string starting from Index is a prefix of
  5107. // str.
  5108. // If a match is found, true value is returned and Index is updated to the next character to be parsed.
  5109. // Otherwise, Index is unchanged.
  5110. //
  5111. internal bool Match(string str)
  5112. {
  5113. if (++Index >= Length)
  5114. {
  5115. return (false);
  5116. }
  5117. if (str.Length > (Value.Length - Index))
  5118. {
  5119. return false;
  5120. }
  5121. if (m_info.Compare(Value.Slice(Index, str.Length), str, CompareOptions.Ordinal) == 0)
  5122. {
  5123. // Update the Index to the end of the matching string.
  5124. // So the following GetNext()/Match() opeartion will get
  5125. // the next character to be parsed.
  5126. Index += (str.Length - 1);
  5127. return (true);
  5128. }
  5129. return (false);
  5130. }
  5131. internal bool Match(char ch)
  5132. {
  5133. if (++Index >= Length)
  5134. {
  5135. return (false);
  5136. }
  5137. if (Value[Index] == ch)
  5138. {
  5139. m_current = ch;
  5140. return (true);
  5141. }
  5142. Index--;
  5143. return (false);
  5144. }
  5145. //
  5146. // Actions: From the current position, try matching the longest word in the specified string array.
  5147. // E.g. words[] = {"AB", "ABC", "ABCD"}, if the current position points to a substring like "ABC DEF",
  5148. // MatchLongestWords(words, ref MaxMatchStrLen) will return 1 (the index), and maxMatchLen will be 3.
  5149. // Returns:
  5150. // The index that contains the longest word to match
  5151. // Arguments:
  5152. // words The string array that contains words to search.
  5153. // maxMatchStrLen [in/out] the initialized maximum length. This parameter can be used to
  5154. // find the longest match in two string arrays.
  5155. //
  5156. internal int MatchLongestWords(string[] words, ref int maxMatchStrLen)
  5157. {
  5158. int result = -1;
  5159. for (int i = 0; i < words.Length; i++)
  5160. {
  5161. string word = words[i];
  5162. int matchLength = word.Length;
  5163. if (MatchSpecifiedWords(word, false, ref matchLength))
  5164. {
  5165. if (matchLength > maxMatchStrLen)
  5166. {
  5167. maxMatchStrLen = matchLength;
  5168. result = i;
  5169. }
  5170. }
  5171. }
  5172. return (result);
  5173. }
  5174. //
  5175. // Get the number of repeat character after the current character.
  5176. // For a string "hh:mm:ss" at Index of 3. GetRepeatCount() = 2, and Index
  5177. // will point to the second ':'.
  5178. //
  5179. internal int GetRepeatCount()
  5180. {
  5181. char repeatChar = Value[Index];
  5182. int pos = Index + 1;
  5183. while ((pos < Length) && (Value[pos] == repeatChar))
  5184. {
  5185. pos++;
  5186. }
  5187. int repeatCount = (pos - Index);
  5188. // Update the Index to the end of the repeated characters.
  5189. // So the following GetNext() opeartion will get
  5190. // the next character to be parsed.
  5191. Index = pos - 1;
  5192. return (repeatCount);
  5193. }
  5194. // Return false when end of string is encountered or a non-digit character is found.
  5195. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  5196. internal bool GetNextDigit() =>
  5197. ++Index < Length &&
  5198. DateTimeParse.IsDigit(Value[Index]);
  5199. //
  5200. // Get the current character.
  5201. //
  5202. internal char GetChar()
  5203. {
  5204. Debug.Assert(Index >= 0 && Index < Length, "Index >= 0 && Index < len");
  5205. return (Value[Index]);
  5206. }
  5207. //
  5208. // Convert the current character to a digit, and return it.
  5209. //
  5210. internal int GetDigit()
  5211. {
  5212. Debug.Assert(Index >= 0 && Index < Length, "Index >= 0 && Index < len");
  5213. Debug.Assert(DateTimeParse.IsDigit(Value[Index]), "IsDigit(Value[Index])");
  5214. return (Value[Index] - '0');
  5215. }
  5216. //
  5217. // Eat White Space ahead of the current position
  5218. //
  5219. // Return false if end of string is encountered.
  5220. //
  5221. internal void SkipWhiteSpaces()
  5222. {
  5223. // Look ahead to see if the next character
  5224. // is a whitespace.
  5225. while (Index + 1 < Length)
  5226. {
  5227. char ch = Value[Index + 1];
  5228. if (!char.IsWhiteSpace(ch))
  5229. {
  5230. return;
  5231. }
  5232. Index++;
  5233. }
  5234. return;
  5235. }
  5236. //
  5237. // Skip white spaces from the current position
  5238. //
  5239. // Return false if end of string is encountered.
  5240. //
  5241. internal bool SkipWhiteSpaceCurrent()
  5242. {
  5243. if (Index >= Length)
  5244. {
  5245. return (false);
  5246. }
  5247. if (!char.IsWhiteSpace(m_current))
  5248. {
  5249. return (true);
  5250. }
  5251. while (++Index < Length)
  5252. {
  5253. m_current = Value[Index];
  5254. if (!char.IsWhiteSpace(m_current))
  5255. {
  5256. return (true);
  5257. }
  5258. // Nothing here.
  5259. }
  5260. return (false);
  5261. }
  5262. internal void TrimTail()
  5263. {
  5264. int i = Length - 1;
  5265. while (i >= 0 && char.IsWhiteSpace(Value[i]))
  5266. {
  5267. i--;
  5268. }
  5269. Value = Value.Slice(0, i + 1);
  5270. }
  5271. // Trim the trailing spaces within a quoted string.
  5272. // Call this after TrimTail() is done.
  5273. internal void RemoveTrailingInQuoteSpaces()
  5274. {
  5275. int i = Length - 1;
  5276. if (i <= 1)
  5277. {
  5278. return;
  5279. }
  5280. char ch = Value[i];
  5281. // Check if the last character is a quote.
  5282. if (ch == '\'' || ch == '\"')
  5283. {
  5284. if (char.IsWhiteSpace(Value[i - 1]))
  5285. {
  5286. i--;
  5287. while (i >= 1 && char.IsWhiteSpace(Value[i - 1]))
  5288. {
  5289. i--;
  5290. }
  5291. Span<char> result = new char[i + 1];
  5292. result[i] = ch;
  5293. Value.Slice(0, i).CopyTo(result);
  5294. Value = result;
  5295. }
  5296. }
  5297. }
  5298. // Trim the leading spaces within a quoted string.
  5299. // Call this after the leading spaces before quoted string are trimmed.
  5300. internal void RemoveLeadingInQuoteSpaces()
  5301. {
  5302. if (Length <= 2)
  5303. {
  5304. return;
  5305. }
  5306. int i = 0;
  5307. char ch = Value[i];
  5308. // Check if the last character is a quote.
  5309. if (ch == '\'' || ch == '\"')
  5310. {
  5311. while ((i + 1) < Length && char.IsWhiteSpace(Value[i + 1]))
  5312. {
  5313. i++;
  5314. }
  5315. if (i != 0)
  5316. {
  5317. Span<char> result = new char[Value.Length - i];
  5318. result[0] = ch;
  5319. Value.Slice(i + 1).CopyTo(result.Slice(1));
  5320. Value = result;
  5321. }
  5322. }
  5323. }
  5324. internal DTSubString GetSubString()
  5325. {
  5326. DTSubString sub = new DTSubString();
  5327. sub.index = Index;
  5328. sub.s = Value;
  5329. while (Index + sub.length < Length)
  5330. {
  5331. DTSubStringType currentType;
  5332. char ch = Value[Index + sub.length];
  5333. if (ch >= '0' && ch <= '9')
  5334. {
  5335. currentType = DTSubStringType.Number;
  5336. }
  5337. else
  5338. {
  5339. currentType = DTSubStringType.Other;
  5340. }
  5341. if (sub.length == 0)
  5342. {
  5343. sub.type = currentType;
  5344. }
  5345. else
  5346. {
  5347. if (sub.type != currentType)
  5348. {
  5349. break;
  5350. }
  5351. }
  5352. sub.length++;
  5353. if (currentType == DTSubStringType.Number)
  5354. {
  5355. // Incorporate the number into the value
  5356. // Limit the digits to prevent overflow
  5357. if (sub.length > DateTimeParse.MaxDateTimeNumberDigits)
  5358. {
  5359. sub.type = DTSubStringType.Invalid;
  5360. return sub;
  5361. }
  5362. int number = ch - '0';
  5363. Debug.Assert(number >= 0 && number <= 9, "number >= 0 && number <= 9");
  5364. sub.value = sub.value * 10 + number;
  5365. }
  5366. else
  5367. {
  5368. // For non numbers, just return this length 1 token. This should be expanded
  5369. // to more types of thing if this parsing approach is used for things other
  5370. // than numbers and single characters
  5371. break;
  5372. }
  5373. }
  5374. if (sub.length == 0)
  5375. {
  5376. sub.type = DTSubStringType.End;
  5377. return sub;
  5378. }
  5379. return sub;
  5380. }
  5381. internal void ConsumeSubString(DTSubString sub)
  5382. {
  5383. Debug.Assert(sub.index == Index, "sub.index == Index");
  5384. Debug.Assert(sub.index + sub.length <= Length, "sub.index + sub.length <= len");
  5385. Index = sub.index + sub.length;
  5386. if (Index < Length)
  5387. {
  5388. m_current = Value[Index];
  5389. }
  5390. }
  5391. }
  5392. internal enum DTSubStringType
  5393. {
  5394. Unknown = 0,
  5395. Invalid = 1,
  5396. Number = 2,
  5397. End = 3,
  5398. Other = 4,
  5399. }
  5400. internal ref struct DTSubString
  5401. {
  5402. internal ReadOnlySpan<char> s;
  5403. internal int index;
  5404. internal int length;
  5405. internal DTSubStringType type;
  5406. internal int value;
  5407. internal char this[int relativeIndex]
  5408. {
  5409. get
  5410. {
  5411. return s[index + relativeIndex];
  5412. }
  5413. }
  5414. }
  5415. //
  5416. // The buffer to store the parsing token.
  5417. //
  5418. internal
  5419. struct DateTimeToken
  5420. {
  5421. internal DateTimeParse.DTT dtt; // Store the token
  5422. internal TokenType suffix; // Store the CJK Year/Month/Day suffix (if any)
  5423. internal int num; // Store the number that we are parsing (if any)
  5424. }
  5425. //
  5426. // The buffer to store temporary parsing information.
  5427. //
  5428. internal
  5429. unsafe struct DateTimeRawInfo
  5430. {
  5431. private int* num;
  5432. internal int numCount;
  5433. internal int month;
  5434. internal int year;
  5435. internal int dayOfWeek;
  5436. internal int era;
  5437. internal DateTimeParse.TM timeMark;
  5438. internal double fraction;
  5439. internal bool hasSameDateAndTimeSeparators;
  5440. internal void Init(int* numberBuffer)
  5441. {
  5442. month = -1;
  5443. year = -1;
  5444. dayOfWeek = -1;
  5445. era = -1;
  5446. timeMark = DateTimeParse.TM.NotSet;
  5447. fraction = -1;
  5448. num = numberBuffer;
  5449. }
  5450. internal unsafe void AddNumber(int value)
  5451. {
  5452. num[numCount++] = value;
  5453. }
  5454. internal unsafe int GetNumber(int index)
  5455. {
  5456. return num[index];
  5457. }
  5458. }
  5459. internal enum ParseFailureKind
  5460. {
  5461. None = 0,
  5462. ArgumentNull = 1,
  5463. Format = 2,
  5464. FormatWithParameter = 3,
  5465. FormatWithOriginalDateTime = 4,
  5466. FormatWithFormatSpecifier = 5,
  5467. FormatWithOriginalDateTimeAndParameter = 6,
  5468. FormatBadDateTimeCalendar = 7, // FormatException when ArgumentOutOfRange is thrown by a Calendar.TryToDateTime().
  5469. };
  5470. [Flags]
  5471. internal enum ParseFlags
  5472. {
  5473. HaveYear = 0x00000001,
  5474. HaveMonth = 0x00000002,
  5475. HaveDay = 0x00000004,
  5476. HaveHour = 0x00000008,
  5477. HaveMinute = 0x00000010,
  5478. HaveSecond = 0x00000020,
  5479. HaveTime = 0x00000040,
  5480. HaveDate = 0x00000080,
  5481. TimeZoneUsed = 0x00000100,
  5482. TimeZoneUtc = 0x00000200,
  5483. ParsedMonthName = 0x00000400,
  5484. CaptureOffset = 0x00000800,
  5485. YearDefault = 0x00001000,
  5486. Rfc1123Pattern = 0x00002000,
  5487. UtcSortPattern = 0x00004000,
  5488. }
  5489. //
  5490. // This will store the result of the parsing. And it will be eventually
  5491. // used to construct a DateTime instance.
  5492. //
  5493. internal
  5494. ref struct DateTimeResult
  5495. {
  5496. internal int Year;
  5497. internal int Month;
  5498. internal int Day;
  5499. //
  5500. // Set time default to 00:00:00.
  5501. //
  5502. internal int Hour;
  5503. internal int Minute;
  5504. internal int Second;
  5505. internal double fraction;
  5506. internal int era;
  5507. internal ParseFlags flags;
  5508. internal TimeSpan timeZoneOffset;
  5509. internal Calendar calendar;
  5510. internal DateTime parsedDate;
  5511. internal ParseFailureKind failure;
  5512. internal string failureMessageID;
  5513. internal object failureMessageFormatArgument;
  5514. internal string failureArgumentName;
  5515. internal ReadOnlySpan<char> originalDateTimeString;
  5516. internal ReadOnlySpan<char> failedFormatSpecifier;
  5517. internal void Init(ReadOnlySpan<char> originalDateTimeString)
  5518. {
  5519. this.originalDateTimeString = originalDateTimeString;
  5520. Year = -1;
  5521. Month = -1;
  5522. Day = -1;
  5523. fraction = -1;
  5524. era = -1;
  5525. }
  5526. internal void SetDate(int year, int month, int day)
  5527. {
  5528. Year = year;
  5529. Month = month;
  5530. Day = day;
  5531. }
  5532. internal void SetBadFormatSpecifierFailure()
  5533. {
  5534. SetBadFormatSpecifierFailure(ReadOnlySpan<char>.Empty);
  5535. }
  5536. internal void SetBadFormatSpecifierFailure(ReadOnlySpan<char> failedFormatSpecifier)
  5537. {
  5538. this.failure = ParseFailureKind.FormatWithFormatSpecifier;
  5539. this.failureMessageID = nameof(SR.Format_BadFormatSpecifier);
  5540. this.failedFormatSpecifier = failedFormatSpecifier;
  5541. }
  5542. internal void SetBadDateTimeFailure()
  5543. {
  5544. this.failure = ParseFailureKind.FormatWithOriginalDateTime;
  5545. this.failureMessageID = nameof(SR.Format_BadDateTime);
  5546. this.failureMessageFormatArgument = null;
  5547. }
  5548. internal void SetFailure(ParseFailureKind failure, string failureMessageID)
  5549. {
  5550. this.failure = failure;
  5551. this.failureMessageID = failureMessageID;
  5552. this.failureMessageFormatArgument = null;
  5553. }
  5554. internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument)
  5555. {
  5556. this.failure = failure;
  5557. this.failureMessageID = failureMessageID;
  5558. this.failureMessageFormatArgument = failureMessageFormatArgument;
  5559. }
  5560. internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument, string failureArgumentName)
  5561. {
  5562. this.failure = failure;
  5563. this.failureMessageID = failureMessageID;
  5564. this.failureMessageFormatArgument = failureMessageFormatArgument;
  5565. this.failureArgumentName = failureArgumentName;
  5566. }
  5567. }
  5568. // This is the helper data structure used in ParseExact().
  5569. internal struct ParsingInfo
  5570. {
  5571. internal Calendar calendar;
  5572. internal int dayOfWeek;
  5573. internal DateTimeParse.TM timeMark;
  5574. internal bool fUseHour12;
  5575. internal bool fUseTwoDigitYear;
  5576. internal bool fAllowInnerWhite;
  5577. internal bool fAllowTrailingWhite;
  5578. internal bool fCustomNumberParser;
  5579. internal DateTimeParse.MatchNumberDelegate parseNumberDelegate;
  5580. internal void Init()
  5581. {
  5582. dayOfWeek = -1;
  5583. timeMark = DateTimeParse.TM.NotSet;
  5584. }
  5585. }
  5586. //
  5587. // The type of token that will be returned by DateTimeFormatInfo.Tokenize().
  5588. //
  5589. internal enum TokenType
  5590. {
  5591. // The valid token should start from 1.
  5592. // Regular tokens. The range is from 0x00 ~ 0xff.
  5593. NumberToken = 1, // The number. E.g. "12"
  5594. YearNumberToken = 2, // The number which is considered as year number, which has 3 or more digits. E.g. "2003"
  5595. Am = 3, // AM timemark. E.g. "AM"
  5596. Pm = 4, // PM timemark. E.g. "PM"
  5597. MonthToken = 5, // A word (or words) that represents a month name. E.g. "March"
  5598. EndOfString = 6, // End of string
  5599. DayOfWeekToken = 7, // A word (or words) that represents a day of week name. E.g. "Monday" or "Mon"
  5600. TimeZoneToken = 8, // A word that represents a timezone name. E.g. "GMT"
  5601. EraToken = 9, // A word that represents a era name. E.g. "A.D."
  5602. DateWordToken = 10, // A word that can appear in a DateTime string, but serves no parsing semantics. E.g. "de" in Spanish culture.
  5603. UnknownToken = 11, // An unknown word, which signals an error in parsing.
  5604. HebrewNumber = 12, // A number that is composed of Hebrew text. Hebrew calendar uses Hebrew digits for year values, month values, and day values.
  5605. JapaneseEraToken = 13, // Era name for JapaneseCalendar
  5606. TEraToken = 14, // Era name for TaiwanCalendar
  5607. IgnorableSymbol = 15, // A separator like "," that is equivalent to whitespace
  5608. // Separator tokens.
  5609. SEP_Unk = 0x100, // Unknown separator.
  5610. SEP_End = 0x200, // The end of the parsing string.
  5611. SEP_Space = 0x300, // Whitespace (including comma).
  5612. SEP_Am = 0x400, // AM timemark. E.g. "AM"
  5613. SEP_Pm = 0x500, // PM timemark. E.g. "PM"
  5614. SEP_Date = 0x600, // date separator. E.g. "/"
  5615. SEP_Time = 0x700, // time separator. E.g. ":"
  5616. SEP_YearSuff = 0x800, // Chinese/Japanese/Korean year suffix.
  5617. SEP_MonthSuff = 0x900, // Chinese/Japanese/Korean month suffix.
  5618. SEP_DaySuff = 0xa00, // Chinese/Japanese/Korean day suffix.
  5619. SEP_HourSuff = 0xb00, // Chinese/Japanese/Korean hour suffix.
  5620. SEP_MinuteSuff = 0xc00, // Chinese/Japanese/Korean minute suffix.
  5621. SEP_SecondSuff = 0xd00, // Chinese/Japanese/Korean second suffix.
  5622. SEP_LocalTimeMark = 0xe00, // 'T', used in ISO 8601 format.
  5623. SEP_DateOrOffset = 0xf00, // '-' which could be a date separator or start of a time zone offset
  5624. RegularTokenMask = 0x00ff,
  5625. SeparatorTokenMask = 0xff00,
  5626. }
  5627. }