Convert dateTime to ISO format yyyy-mm-dd hh:mm:ss in C# ...

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

NET/C# to convert a datetime object to ISO 8601 format yyyy-mm-dd hh:mm:ss? Or do I need to do some string manipulation to get the date string? 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 ConvertdateTimetoISOformatyyyy-mm-ddhh:mm:ssinC#[duplicate] AskQuestion Asked 12years,3monthsago Modified 5years,3monthsago Viewed 148ktimes 45 4 Thisquestionalreadyhasanswershere: GivenaDateTimeobject,howdoIgetanISO8601dateinstringformat? (18answers) Closed5yearsago. Isthereastandardwayin.NET/C#toconvertadatetimeobjecttoISO8601formatyyyy-mm-ddhh:mm:ss? OrdoIneedtodosomestringmanipulationtogetthedatestring? c#.net Share Follow editedJun18,2015at16:16 PeterMortensen 29.8k2121goldbadges9898silverbadges124124bronzebadges askedDec16,2009at7:15 ChinChin 12.1k3636goldbadges9999silverbadges152152bronzebadges 1 5 ThisisnotISOformat.you'remissingtheT(andoptionally-timezone) – RoyiNamir Jun15,2015at5:52 Addacomment  |  6Answers 6 Sortedby: Resettodefault Highestscore(default) Datemodified(newestfirst) Datecreated(oldestfirst) 78 TousethestrictISO8601,youcanusethes(Sortable)formatstring: myDate.ToString("s");//example2009-06-15T13:45:30 It'sashort-handtothiscustomformatstring: myDate.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss"); Andofcourse,youcanbuildyourowncustomformatstrings. Moreinfo: StandardDateandTimeformatstrings CustomDateandTimeFormatStrings Share Follow editedDec16,2009at7:27 answeredDec16,2009at7:18 ChristianC.SalvadóChristianC.Salvadó 761k178178goldbadges909909silverbadges831831bronzebadges 1 1 Thisshouldbetheacceptedsolution. – JamesG Jun20,2017at5:28 Addacomment  |  60 Thereisnostandardformatforthereadable8601format.Youcanuseacustomformat: theDate.ToString("yyyy-MM-ddHH':'mm':'ss") (Thestandardformat"s"willgiveyoua"T"betweenthedateandthetime,notaspace.) Share Follow answeredDec16,2009at7:22 GuffaGuffa 662k102102goldbadges700700silverbadges980980bronzebadges 9 Notethatthiswilluse/asdateseparatorinplacesliketheUSandFrance(asin2009/12/1608:42:16) – FredrikMörk Dec16,2009at7:42 6 @Fredrik:No,itwon't.IfIwouldhaveused/intheformatthenitwouldhaveusetheculturespecificdateseparator,but-isaliteralcharacterandwon'tbereplacedbyanythingelse. – Guffa Dec16,2009at8:00 @Guffa:youareright,ofcourse.Mixeditup,mybad. – FredrikMörk Dec16,2009at8:13 1 Whatabout"u"nowadays?SeeDateTimeFormatInfo.UniversalSortableDateTimePatternProperty – johv Jan18,2013at16:16 1 Thisisincorrect.ThestandardrequiresaTwhencombiningdateandtime.Itcanonlybeomittedwhenbothpartiesagree.Usingthisdirectlywithabrowserwillfail,forinstance.Ref:en.wikipedia.org/wiki/… – oligofren Nov29,2016at20:50  |  Show4morecomments 16 Toaddalittlebitmoreinformationthatconfusedme; Ihadalwaysthoughtthesameresultcouldbeachievedlikeso; theDate.ToString("yyyy-MM-ddHH:mm:ss") However,IfyourCurrentCulturedoesn'tuseacolon(:)asthehourseparator,andinsteadusesafull-stop(.)itcouldreturnasfollow: 2009-06-1513.45.30 Justwantedtoaddwhytheanswerprovidedneedstobeasitis; theDate.ToString("yyyy-MM-ddHH':'mm':'ss") :-) Share Follow answeredFeb24,2014at17:53 MickPMickP 18511silverbadge44bronzebadges 3 ThisworkedperfectlyconvertingaC#DateTimetoaSQLServersmalldatetime.Thestringswereacceptedintheinsertstatement. – octopusgrabbus Dec4,2014at23:05 ThisisnotISO8601.'T'mustseparateDateandtime. – percebus May10,2016at20:16 Theyarecontinuouslygivingmetheerrorconversion. – Istorn Mar28,2019at9:11 Addacomment  |  9 date.ToString("o")//TheRound-trip("O","o")FormatSpecifier date.ToString("s")//TheSortable("s")FormatSpecifier,conformingtoISO86801 MSDNStandardDateandTimeFormatStrings Share Follow editedNov29,2016at20:52 oligofren 17.5k1414goldbadges8282silverbadges151151bronzebadges answeredDec12,2013at12:17 LuisLuis 15811silverbadge44bronzebadges Addacomment  |  0 ForthosewhoareusingthisformatallthetimmelikemeIdidanextensionmethod. IjustwantedtosharebecauseIthinkitcanbeusefulltoyou. ///

///ConvertadatetoahumanreadableISOdatetimeformat.ie.2012-12-1223:01:12 ///thismethodmustbeputinastaticclass.Thiswillappearasanavailablefunction ///oneverydatetimeobjectsifyourstaticclassnamespaceisdeclared. /// publicstaticstringToIsoReadable(thisDateTimedateTime) { returndateTime.ToString("yyyy-MM-ddHH':'mm':'ss"); } Share Follow answeredMay27,2013at8:57 codeacodea 1,19911goldbadge1212silverbadges2929bronzebadges Addacomment  |  0 TheDateTime::ToString()methodhasastringformatterthatcanbeusedtooutputdatetimeinanyrequiredformat.SeeDateTime.ToStringMethod(String)formoreinformation. Share Follow editedOct6,2016at11:11 PeterMortensen 29.8k2121goldbadges9898silverbadges124124bronzebadges answeredDec16,2009at7:22 A9S6A9S6 6,3351010goldbadges4949silverbadges8181bronzebadges 1 myDate.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss");-doesnotworkforme.MaybetryString.Format()? – user1040323 Nov29,2012at11:09 Addacomment  |  Nottheansweryou'relookingfor?Browseotherquestionstaggedc#.netoraskyourownquestion. TheOverflowBlog AIandnanotechnologyareworkingtogethertosolvereal-worldproblems FeaturedonMeta WhatgoesintositesponsorshipsonSE? StackExchangeQ&AaccesswillnotberestrictedinRussia Shouldweburninatethe[term]tag? NewUserExperience:DeepDiveintoourResearchontheStagingGround–How... AskWizardforNewUsersFeatureTestisnowLive Linked 942 GivenaDateTimeobject,howdoIgetanISO8601dateinstringformat? 0 ASP.NETServer-sidedatetimeproblem 0 ConvertHours,minsandsecsintoHH:MM:SSformat -1 DateTimeacrossanyculture Related 2102 HowdoIcalculatesomeone'sagebasedonaDateTimetypebirthday? 2479 Deepcloningobjects 942 GivenaDateTimeobject,howdoIgetanISO8601dateinstringformat? 2313 HowdoIgetaconsistentbyterepresentationofstringsinC#withoutmanuallyspecifyinganencoding? 1336 LINQ'sDistinct()onaparticularproperty 2149 GetintvaluefromenuminC# 1063 HowtoconvertUTF-8byte[]tostring 1309 JavaScriptSerializer-JSONserializationofenumasstring 931 DateTimevsDateTimeOffset 1134 HowdoIturnaC#objectintoaJSONstringin.NET? HotNetworkQuestions Ifplanetsareellipsoidswhydon'twehave3diameters? IfplayerAisincheckbuthasamovewhichwillcheckmateplayerBwithoutexitingcheck,isthatmovelegal? Sandboxoverflow Lookingforaseriesaboutyounggirlwhowascreatedinalabbyhermum Reartiregetsflateverymonthforunknownreasons Isthereaneasywayofdrawingapartofacircleusedinacomplexcontour? Isthereagoodmathematicalexplanationforwhyorbitallengthsintheperiodictableareperfectsquaresdoubled? Isthereaconventionfordocumentingaschematicwithnotes? FeaturesofGeneralRelativityapplicableonlyto3+1dimensions? HowcanIjudgethe"strength"ofalicence? Whatisthecollectivename/termgiventothepartofacurrencyvaluebeforeandafterthepoint? Minussignnotaligningwithfraction Doesitmakesensetoprovidea'CRediTstatement'whenIamthesoleauthor? Whatdowedowhenweaccidentallyblockan"unblockable"creature? Howtogetamotorcycletoaskillstest Howtomotivatestafftoattendapaidcertification? Whyarerealphotonssomuchlessefficientincarryingmomentumthanvirtualphotons? HowDoesOrbitalWarfareWork? ReturningMTBrider,lookingforadviceonpurchasinganewMTB Haskellcomparingtwolists'lengthsbutoneofthemisinfinite? HowcanIpreservebooks,butkeepthemaccessible? Convertbetweengraphrepresentations Helpidentifyingthisanimal Inthesentence"Thetablewassetforlunch"is"set"averboranadjective? morehotquestions lang-cs Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?