DateTimeParse.cs 247 KB

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