Convert DateTime in C# to yyyy-MM-dd format and Store it to ...
文章推薦指數: 80 %
Use DateTime.Now.ToString("yyyy-MM-dd h:mm tt"); . See this. 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 ConvertDateTimeinC#toyyyy-MM-ddformatandStoreittoMySqlDateTimeField AskQuestion Asked 8years,5monthsago Modified 7monthsago Viewed 363ktimes 56 8 IamtryingtoconvertDateTimeformattoyyyy-MM-ddformatandstoreittoDateTimeobject.ButitgivesmetheSystemDateTimeformatthatisMM/dd/yyyy. Iamusingfollowingcodetoconvert. stringdateTime=DateTime.Now.ToString(); stringcreateddate=Convert.ToDateTime(dateTime).ToString("yyyy-MM-ddh:mmtt"); DateTimedt=DateTime.ParseExact(createddate,"yyyy-MM-ddh:mmtt",CultureInfo.InvariantCulture); butnonoftheabovelineconvertsintothespecifiedformat. Cananyonehelptosolvethis. IamgettingtheDateTimefromoneapplicationandpassingthisobjecttootherapplicationandThatapplicationisstoringthatdateintoMySql'sDateTimefieldwhichisintheformat"yyyy-MM-dd". ThisiswhyIhavepostedthisquestion. Project1hasclassfromthatIamgettingthedate. andtheprocessorclasswhichisthemiddlewareoftheapplicationitprocessestheDateTimeformattoconvertinspecificformat.AndpassestotheOtherprojectwhichconsumestheDateTimeandstoresthatintheMySqlfield. c#mysqldatedatetime Share Follow editedOct10,2013at13:32 RahulGokani askedOct10,2013at12:59 RahulGokaniRahulGokani 1,62844goldbadges2525silverbadges4242bronzebadges 8 3 Why?Howit'sstoredintheobjectshouldmakeanydifferenceinyourcode.Justusetheproperculturewhendoinganycomparisons. – Smeegs Oct10,2013at13:03 6 Datatimedosen'thaveaformat,theformatisappliedtohowyouwanttodisplayit(ToString()) – Bolu Oct10,2013at13:05 IamgettingthedatefromotherapplicationandpassthatdatetotheotherpageandfromthereIamtryingtostorethatdateinMySqldateTimefield. – RahulGokani Oct10,2013at13:05 @RahulGokanithenyoushouldhavespecifiedthatinyourquestion.Isuggestyouupdateittoreflectthis,aswellasshowingwhatcodeyouhavetriedtoassignitwhereyouwanttouseit. – crashmstr Oct10,2013at13:10 4 Youshouldreallydeletethisquestionandask"HowdoIproperlystoreadatetimeobjectinamysqldatecolumn".You'refocusingonwhatyouperceiveasthesolution,butyou'rereallyjustlookingatasymptom,nottheproblem. – Smeegs Oct10,2013at13:14 | Show3morecomments 7Answers 7 Sortedby: Resettodefault Highestscore(default) Datemodified(newestfirst) Datecreated(oldestfirst) 115 UseDateTime.Now.ToString("yyyy-MM-ddh:mmtt");.Seethis. Share Follow answeredOct10,2013at13:00 AlexAlex 1,58711goldbadge1111silverbadges66bronzebadges 6 3 IwanttostoreconverteddateintotheDateTimeformatIamabletogetthatstringvalueasspecifiedformat. – RahulGokani Oct10,2013at13:01 1 Youcan'tchangehowDateTimewillstoreyourdate.Butwhenyouneedtooutputthisdate,ortosaveindatabaseinspecificformat,useToStringtocreateneededformat – Alex Oct10,2013at13:03 @RahulGokaniDateTimedoesn'tstorethedatainanyformatlikethat.Datawillbestoredinseparateintegerproperties(Month,Year,Date,Houretc),formatisjustthestringrepresentation. – FedorHajdu Oct10,2013at13:04 Theinternalformatoftheobjectisnotsomethingyoucanset.Youcanformatitasyouwantwhenyouconvertittoastringasdescribedabove.Maybeyoucouldexplainwhatyouaretryingtoaccomplish? – automatic Oct10,2013at13:04 Idon'tgetwhythestorageformatevenmatterstoyou.IfyouwanttoprintouttheDateyoucanjustformatitwithAlex'ssuggestedway.IfyouwanttoworkwiththeObjectitselfitsurelydoesn'tmatteratall.YougotalltheHour/Minute/etc.propertiesforthat. – SKull Oct10,2013at13:05 | Show1morecomment 27 Wecanusethebelowitsverysimple. Date.ToString("yyyy-MM-dd"); Share Follow editedFeb7,2014at7:17 BabyGroot 4,6173939goldbadges5252silverbadges6969bronzebadges answeredFeb7,2014at6:56 sanjay.arora29sanjay.arora29 27911goldbadge44silverbadges44bronzebadges 2 1 HewantstosaveittoaDateTimeobject,Theabovecodegivesyoustring,WhichyouneedtoconvertbacktoDateTimeandthatdoesn'tworkstraightforward. – RajshekarReddy Oct17,2015at7:50 4 ifsomebodyheregetsthefollowingerror:"NooverloadformethodToStringtakes1arguments"thentrythis:((DateTime)Date).ToString("yyyy-MM-dd"); – Djeroen Feb3,2016at16:01 Addacomment | 6 TrysettingacustomCultureInfoforCurrentCultureandCurrentUICulture. Globalization.CultureInfocustomCulture=newGlobalization.CultureInfo("en-US",true); customCulture.DateTimeFormat.ShortDatePattern="yyyy-MM-ddh:mmtt"; System.Threading.Thread.CurrentThread.CurrentCulture=customCulture; System.Threading.Thread.CurrentThread.CurrentUICulture=customCulture; DateTimenewDate=System.Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-ddh:mmtt")); Share Follow answeredJun14,2016at11:27 AsankaMadushanAsankaMadushan 43377silverbadges1717bronzebadges Addacomment | 5 Haveyoutried? varisoDateTimeFormat=CultureInfo.InvariantCulture.DateTimeFormat; //"2013-10-10T22:10:00" dateValue.ToString(isoDateTimeFormat.SortableDateTimePattern); //"2013-10-1022:10:00Z" dateValue.ToString(isoDateTimeFormat.UniversalSortableDateTimePattern) Alsotryusingparameterswhenyoustorethec#datetimevalueinthemySqldatabase,thismighthelp. Share Follow answeredOct10,2013at13:16 DrewbieDooDrewbieDoo 5911silverbadge11bronzebadge 3 Ihavetrieditbutitisgivingmethestringformatonly.IneedtostorethatinDateTime. – RahulGokani Oct10,2013at13:21 Howareyoustoringit?ImeanareyoupassingparameterswithvalueorusinganORM? – DrewbieDoo Oct10,2013at13:25 Thislookslikeaduplicateofthisquery,hencemysuggestionstackoverflow.com/questions/3633262/… – DrewbieDoo Oct10,2013at13:30 Addacomment | 5 Iknowthisisanoldthread,buttoallnewcomers,there'sanewsimplifiedsyntax(Intellisensehighlighteditforme,notsurehownewthisfeatureis,butmyguessis.NET5.0) DateTimedate=DateTime.Now; stringcreatedDate=$"{date:yyyy-MM-dd}"; Maybedoesn'tlooksimplifiedinthisexample,butwhenconcatenatingalongmessage,it'sreallyconvenient. Share Follow answeredJul26,2021at15:05 KifoPLKifoPL 43333silverbadges1313bronzebadges Addacomment | 2 GetDateTimeFormatscanparseDateTimetodifferentformats. Exampleto"yyyy-MM-dd"format. SomeDate.Value.GetDateTimeFormats()[5] GetDateTimeFormats Share Follow editedMar9,2017at22:21 AdamV 6,02833goldbadges3838silverbadges5151bronzebadges answeredMar9,2017at21:55 YKCYKC 6122bronzebadges Addacomment | 0 Trythis! DateTimedt=newDateTime(DateTime.Now.Year,DateTime.Now.Month,DateTime.Now.Day,DateTime.Now.Hour,DateTime.Now.Minute,DateTime.Now.Ticks) Share Follow answeredJun28,2021at15:19 PrasannaPrasanna 1 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#mysqldatedatetimeoraskyourownquestion. TheOverflowBlog AIandnanotechnologyareworkingtogethertosolvereal-worldproblems FeaturedonMeta WhatgoesintositesponsorshipsonSE? StackExchangeQ&AaccesswillnotberestrictedinRussia Shouldweburninatethe[term]tag? NewUserExperience:DeepDiveintoourResearchontheStagingGround–How... AskWizardforNewUsersFeatureTestisnowLive Linked 32 ConvertDateTimeforMySQLusingC# 0 ASP.NETvb.netconvertcalendardateformatinMonth/Day/YeartoDateobjectwithDay/Month/Year Related 987 HowdoyousetadefaultvalueforaMySQLDatetimecolumn? 2966 ShouldIusethedatetimeortimestampdatatypeinMySQL? 780 Howtocheckwhetheranobjectisadate? 1474 WherecanIfinddocumentationonformattingadateinJavaScript? 1305 YYYY-MM-DDformatdateinshellscript 827 ConvertdatetodatetimeinPython 709 C#DateTimeto"YYYYMMDDHHMMSS"format 679 HowtomakeatimezoneawaredatetimeobjectinPython? 204 Convertdd-mm-yyyystringtodate 391 ConvertPandasColumntoDateTime HotNetworkQuestions DrawtheUkrainianFlag HowDoesOrbitalWarfareWork? WhatisthispairofrectangularpatternsontheEnterprise-D'sexterior? MeshgenerationforadiscretesetofpointsinListContourPlot? Helpidentifyingthisanimal ReturningMTBrider,lookingforadviceonpurchasinganewMTB Getvaluefrom\foreach CouldPutinbeimpeached? Whydoesn'ttheUSsendairplanestoUkraine,whenRussianssentMIGstoVietnamduringVietnamwar? WhatcanweeatinthelateCretaceous? Checkifacommandexistsrevisited Isthereaconventionfordocumentingaschematicwithnotes? Whenandhowtoleaveafacultypositionforanewdepartment/universityorindustry WhatUSSupremeCourtruling(s)addresstheSEC'sproposed"Scope3disclosurerule"thatcompaniesmuststatetheirclimatechangeimpact? Aproverbthatexpressestheideathatanunaddressedproblemwillleadtoconsequences? HowcanIcreateacomma-separatedlistofcharactersfromatextstring? Hotmeteoritelandsonbed Isthereanyexampleofadependentproductthatmakessenseinanon-type-theorycontext? Meaningof"orwehaveheadphonesorwedon't,so..." CanIsubmitmytaxesinmultipleenvelopes? HasRowlingeverrecognisedmistakesorinconsistencies? D&DGroupGoesTooSlowly FeaturesofGeneralRelativityapplicableonlyto3+1dimensions? IfplayerAisincheckbuthasamovewhichwillcheckmateplayerBwithoutexitingcheck,isthatmovelegal? morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. default Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings
延伸文章資訊
- 1自訂日期與時間格式字串 - Microsoft Docs
DateTime date1 = new DateTime(70, 08, 04); Console.WriteLine(date1.ToString("MM/dd/yyyy g", Cultu...
- 2發問
Format("{0:yyyy/MM/dd HH:MM:ss}",時間) ... 如何把2012/2/9 下午01:39:11用string.format改成2012/02/09 13:39:1...
- 3Date and Time Conversions Using SQL Server
- 4Checking Date format from a string in C# - Stack Overflow
- 5DateTime.ToString 方法(System) | Microsoft Docs
目前DateTime 物件值的字串表示,如 format 及 provider 所指定。 ... Aug 17 '00 * dddd, MMMM dd :Thursday, August 17 ...