Convert the string with datetime format-"yyyyMMddhhmmssfff ...

文章推薦指數: 80 %
投票人數:10人

string format = "yyyyMMddHHmmssfff"; string dateTime = "20191211034422455"; var x = DateTime.ParseExact(dateTime, format, CultureInfo. Home Public Questions Tags Users Collectives ExploreCollectives FindaJob Jobs Companies Teams StackOverflowforTeams –Collaborateandshareknowledgewithaprivategroup. CreateafreeTeam WhatisTeams? Teams CreatefreeTeam CollectivesonStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. Learnmore Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. Learnmore Convertthestringwithdatetimeformat-"yyyyMMddhhmmssfff"to"DD-MM-YYYYHH:MM)beforeexportingDataTabletoexcel AskQuestion Asked 2years,3monthsago Modified 2years,3monthsago Viewed 3ktimes 2 IamexportingtheresultfromadatabasetoexcelusingExcelPackage(EPPLUSnugetpackage). Thedatetimefieldfromthedatabaseisinstringandintheformat-yyyyMMddhhmmssfffwhichisnotreadableinexcelafterexporting-ex-20191211034422455.Soineedtoconvertthistoreadableformatlike DD-MM-YYYYHH:MMoranyotherreadableformat.Howdoiachieveit.Doineedtoparseeachrowandconvertexplicitly?Andforconversion,doihavetofirstconvertittodatetimeandthentostringagain? MycurrentcodeSnippet //Methodwhichreadsdatafromdatabase using(SqlConnectionsqlcon=newSqlConnection(ConnStrng)) { sqlcon.Open(); stringquery="SelectVehicleid,Speed,DatetimefromVehiclDBkwhereSpeed>30andDatetimebetween'"+startDate+"'and'"+endDate+"'"; SqlDataAdaptersqlda=newSqlDataAdapter(query,sqlcon); valRes=newDataTable(); sqlda.Fill(valRes); DBView.DataSource=valRes; sqlcon.Close(); } //Methodwhichexportsdatawhenuserpressesexportbutton using(ExcelPackagepck=newExcelPackage()) { ExcelWorksheetws=pck.Workbook.Worksheets.Add(DateTime.Now.ToShortDateString()); ws.Cells["A1"].LoadFromDataTable(valRes,true); pck.SaveAs(newFileInfo(savefile.FileName)); } Anyhelpwouldbegreatlyappreciated. AlsoisthereapossibilitythatmaybeicanjustconvertittoDateTimeandexportasDateTimeinsteadofstringtodatetimeandagaintostringbeforeexporting c#datetimedatetime-formatepplusexcelpackage Share Improvethisquestion Follow editedDec16,2019at10:41 SonerGönül 93.7k102102goldbadges195195silverbadges337337bronzebadges askedDec16,2019at8:00 230490230490 51644silverbadges1515bronzebadges 4 Areyousureyou'restoringthesevaluesasstringsinyourdatabase?GooddatabasedesignwouldstorethemasDateTime(orequivalent)objects. – DiplomacyNotWar Dec16,2019at8:03 Yes,itsbeenstoredasstring.Notsurewhythiswasdecidedasthisdatabaseexistsfrombeginning – 230490 Dec16,2019at8:05 Don'tusestrings,usedatesandsetthecorrectdatestyleinstead.Modifyingthecellvaluedoesn'tchangehowit'sformatted.ItcanmakeExceltreatthatvalueasastringinsteadofadatethough,breakinganydate-relatedformulas – PanagiotisKanavos Dec16,2019at8:19 PS:Youdon'ttoloadaDataTable,youcanuseLoadFromDataReader.EvenifyouwantaDataTable,youdon'tneedSqlDataAdaptertodoit – PanagiotisKanavos Dec16,2019at8:22 Addacomment  |  1Answer 1 Sortedby: Resettodefault Highestscore(default) Datemodified(newestfirst) Datecreated(oldestfirst) 3 YouShouldconvertittoDateTimeandthentostringagain. IncaseyougotaDateTimehavingmilliseconds,usethefollowingformatting(Linklivedemohere) stringformat="yyyyMMddHHmmssfff"; stringdateTime="20191211034422455"; varx=DateTime.ParseExact(dateTime,format,CultureInfo.InvariantCulture); varresult=x.ToString("dd-MM-yyyyHH:MM");//Inmyopinion,YoujustconverttoDatetouseinsteadofthentostringlikethis. Share Improvethisanswer Follow editedDec16,2019at8:22 answeredDec16,2019at8:08 NguyễnVănPhongNguyễnVănPhong 12.4k1616goldbadges2828silverbadges5151bronzebadges 5 Doineedtodoitforallrowsexplicitlybeforeexporting? – 230490 Dec16,2019at8:13 1 Justtonit-pick,youdon't"haveto"converttoaDateTime.Youcouldjustdoitusingsubstrings. – HansKilian Dec16,2019at8:17 Thiswon'twork.Excelwilleithernotrecognizethestringasadate,ordosoanduseitsdefaultdateformattinginsteadofthestring'svalue – PanagiotisKanavos Dec16,2019at8:20 Yeah,IfIwereinhisshoes,IcouldjustconverttoDateTimeonlyinsteadofTostring – NguyễnVănPhong Dec16,2019at8:21 Truethat.Iwillconverttodatetimeinsteadofstringagain.@PhongNguyen:inthesolutiongiven,imnotabletopassmydatatable.rows[1][0]asfirstargumenttoparseexact – 230490 Dec16,2019at9:06 Addacomment  |  YourAnswer ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers. Draftsaved Draftdiscarded Signuporlogin SignupusingGoogle SignupusingFacebook SignupusingEmailandPassword Submit Postasaguest Name Email Required,butnevershown PostYourAnswer Discard Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy Nottheansweryou'relookingfor?Browseotherquestionstaggedc#datetimedatetime-formatepplusexcelpackageoraskyourownquestion. TheOverflowBlog AIandnanotechnologyareworkingtogethertosolvereal-worldproblems FeaturedonMeta WhatgoesintositesponsorshipsonSE? StackExchangeQ&AaccesswillnotberestrictedinRussia Shouldweburninatethe[term]tag? NewUserExperience:DeepDiveintoourResearchontheStagingGround–How... AskWizardforNewUsersFeatureTestisnowLive Related 942 GivenaDateTimeobject,howdoIgetanISO8601dateinstringformat? 467 ConvertfromMySQLdatetimetoanotherformatwithPHP 409 ConvertDataFramecolumntypefromstringtodatetime 2 ConvertingaDatetimefromthedatatabletoaspecificformatofstringC#ASP.NET 6 BigqueryDatetimeformatcsvtobigqueryYYYY-MM-DDHH:MM[:SS[.SSSSSS]] 0 ExcelVBA:ConvertDateTimestringtoGermanDateTimeformat(constantstringlength) HotNetworkQuestions HowToshowhiddenFolders/Files DrawtheUkrainianFlag D&DGroupGoesTooSlowly Howtodrainatoiletbowl? WhydoAirForceplanesregularlyflyincircles? Howdoesonerespondto"Quidagis." Minussignnotaligningwithfraction ReturningMTBrider,lookingforadviceonpurchasinganewMTB Isthereagoodmathematicalexplanationforwhyorbitallengthsintheperiodictableareperfectsquaresdoubled? Where'sthecausative'getsstained'in近朱者赤,近墨者黑? Howdoestheprincipleofrelativityimplythatphotonclocksandmechanicalclocksexperiencetimedilationthesameway? Whenandhowtoleaveafacultypositionforanewdepartment/universityorindustry Surprisingapplicationsofthetheoryofgames? IsareturnairticketabsolutelynecessaryforSchengenbusinesstrip? Inacyberpunkworldwherecorporateupperclasscitizenscanworkvirtuallythroughimplants,whywouldtheybuildcorporatemega-skyscrapers? HowDoesOrbitalWarfareWork? Isthereaconventionfordocumentingaschematicwithnotes? JWST-imageacquisition-whatisaditherpattern? WhatUSSupremeCourtruling(s)addresstheSEC'sproposed"Scope3disclosurerule"thatcompaniesmuststatetheirclimatechangeimpact? CouldPutinbeimpeached? Palindromefromthefirst20numbers Extremecoldresistantflora Iturnedabreakeroff,andnowthesecurityalarmsystemwon’tstopbeeping WilllayertolayerleakagehappeninaPCB morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-cs Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?