C# DateTime Format:Working with Date &Time format in C#|

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

You can convert the dateTime to any DateTime format by simply adding the required format in ToString (.ToString(“yyyyMMdd”)) as shown in the above example. Skiptocontent Menu C#DateTimeclassinC#providespropertiesandmethodstoformatdatesindifferentDateTimeformats.ThisarticleexplainshowtoworkwiththeC#DateTimeformat Including TimerandSleepMethods. LetsStartswithC#DateTimeObject– DateTimeisaStructintheSystemnamespace.Ithelpsthedeveloperstoretrieveinformationaboutsystemdate,time,month,year,oreventhedayoftheweek. HowToCreateTheC#DateTimeObject? classProgram { staticvoidMain(string[]args) { //Year,Month,Date DateTimedt=newDateTime(2016,03,07); Console.WriteLine(dt.ToString()); Console.Read(); } } Theoutputoftheaboveprogramwillbe:3/7/201612:00:00AM Ifyouseehereinthisoutputtimeisshownas12:00:00AM(defaulttime).Wehaven’tsetanytimevalueandthusthesystemautomaticallyassigneddefaultvaluestoanhour,minute,andsecond. DateTimeObjectProperties: DateTimedt=newDateTime(2016,03,07); intyear=dt.Year; intmonth=dt.Month; intdate=dt.Day; inthour=dt.Hour; intmin=dt.Minute; intsec=dt.Second; intdayOfWeek=Convert.ToInt32(dt.DayOfWeek); intdayOfYear=dt.DayOfYear; Year Yearpropertyretrievestheyearcomponentofthedaterepresentedbythedate-timeinstance.Itreturnsanintegervalueexpressedasavaluebetween1and9999. Month Monthpropertyretrievesthemonthcomponentofthedaterepresentedbythedate-timeinstance.Itreturnsanintegervalueexpressedasavaluebetween1and12. Day Daypropertyretrievesthedatecomponentofthemonthrepresentedbythedate-timeinstance.Itreturnsanintegervalueexpressedasavaluebetween1and31. Hour Hourpropertyretrievesthehourcomponentofthedaterepresentedbythedate-timeinstance.Itreturnsanintegervalueexpressedasavaluebetween0and23. Minute Minpropertyretrievestheminutecomponentofthedaterepresentedbythedate-timeinstance.Itreturnsanintegervalueexpressedasavaluebetween0and59. Second Secondpropertyretrievesthesecondcomponentofthedaterepresentedbythedate-timeinstance.Itreturnsanintegervalueexpressedasavaluebetween0and59. DayoftheWeek Dayoftheweekpropertyretrievestheenumeratedconstantthatindicatesthedayoftheweekrepresentedbythedate-timeobject.Italsorequirescastingtoacceptintegervalue. DayofYear Dayofyearpropertyretrievesthedayoftheyearrepresentedbythedate-timeobject.Itreturnsanintegervalueexpressedasavaluebetween0and366. NowLetshavealookatbelowcodetoseehowwecanusetheseproperties. DateTimedt=newDateTime(2016,03,07); intyear=dt.Year; intmonth=dt.Month; intdate=dt.Day; inthour=dt.Hour; intmin=dt.Minute; intsec=dt.Second; intdayOfWeek=Convert.ToInt32(dt.DayOfWeek); intdayOfYear=dt.DayOfYear; Console.WriteLine(year); Console.WriteLine(month); Console.WriteLine(date); Console.WriteLine(hour); Console.WriteLine(min); Console.WriteLine(sec); Console.WriteLine(dayOfWeek); Console.WriteLine(dayOfYear); Console.Read(); Theoutputoftheaboveprogramwillbe: Year:2016Month:3Date:7Hour:0Minute:0Second:0 Dayoftheweek:1Dayoftheyear:67 HowToGetCurrentDateTime? DateTimeobjectcontainsanumberofdifferentmethodstoaccesssystemtime.The“Now”methodallowsyoutogetthecurrentsystemtime/dateandevenallowsyoutooperateonit. Syntax: DateTimedt=DateTime.Now; Wecaneasilyconvertittostringtogetthecurrentdate-timeorwecanevenchangetheformatofthedatebyusingthebelowformats. NOTE:Considercurrentdatetimeis7March201611:06:25 Displaydatetimein 24hourformat DateTime.Now.ToString(“dd/MM/yyyyHH:mm:ss”); Ans:07/03/201611:06:25 Note:HHisusedfor24hour format.           hhfor12hourformat Displayam/pmindate timeor12hourformattime.  DateTime.Now.ToString(“hh:mm:ss tt”);  Ans:11:06:25AM  Note: “tt” forAMorPM Displaytimezonein datetime. DateTime.Now.ToString(“hh:mm:ss ttzzz”); Ans: 11:06:25AM+05:30(Here+05:30istimezoneforIndia) Note: zzzisusedto displaytimezone. Showfullmonthname indate. DateTime.Now.ToString(“dd-MMMM-yy”); Ans: 07-March-16 Howtoformatfull daynameindate? DateTime.Now.ToString(“dddd-MMMM-yy”); Ans: Monday-March-16 Note: MMMMforfullmonth name Howtoformatfull yearnameindate? DateTime.Now.ToString(“dddd-MMMM-yyyy”); Ans: Monday-March-2016 Note: yyyyforfourdigit year Toreduce/subtract dateordays DateTime.Now.AddDays(-10) Toadddays DateTime.Now.AddDays(10) C#DateTimeto“YYYYMMDDHHMMSS”format DateTime.Now.ToString(“yyyyMMddHHmmss”); YoucanconvertthedateTimetoanyDateTimeformatbysimplyaddingtherequiredformatinToString(.ToString(“yyyyMMdd”))asshownintheaboveexample.PleasenotethatC#datetimeformatiscase-sensitive.Pleasecheckbelow. y=year,m=minutes/M=months,d=date,h=12hour,H=24hour,s=seconds Let’shavealookatbelowC#DateTimeformatsandtheiroutputs.HereweseeallthepatternsoftheC#DateTime,format,andoutputs. C#DateTimeFormatOutputDateTime.Now.ToString(“MM/dd/yyyyHH:mm”)11/29/201909:11DateTime.Now.ToString(“MM/dd/yyyyhh:mmtt”)11/29/201909:11AMDateTime.Now.ToString(“MM/dd/yyyyH:mm”)11/29/20199:11DateTime.Now.ToString(“MM/dd/yyyyh:mmtt”)11/29/20199:11AMDateTime.Now.ToString(“MM/dd/yyyyHH:mm:ss”)11/29/20199:11:32DateTime.Now.ToString(“MM/dd/yyyy”)11/29/2019DateTime.Now.ToString(“dddd,ddMMMMyyyy”)Friday,29November2019DateTime.Now.ToString(“dddd,ddMMMMyyyyHH:mm”)Friday,29November201909:11DateTime.Now.ToString(“dddd,ddMMMMyyyyhh:mmtt”)Friday,29November201909:11AMDateTime.Now.ToString(“dddd,ddMMMMyyyyh:mm”)Friday,29November20199:11DateTime.Now.ToString(“dddd,ddMMMMyyyyh:mmtt”)Friday,29November20199:11AMDateTime.Now.ToString(“dddd,ddMMMMyyyyHH:mm:ss”)Friday,29November201909:11:32DateTime.Now.ToString(“MMMMdd”)November29DateTime.Now.ToString(“yyyy’-‘MM’-‘dd’T’HH’:’mm’:’ss.fffffffK”)2019-11-29T09:11:32.0839641+05:30DateTime.Now.ToString(“ddd,ddMMMyyyHH’:’mm’:’ss‘GMT'”)Fri,16Nov201909:11:32GMTDateTime.Now.ToString(“yyyy’-‘MM’-‘dd’T’HH’:’mm’:’ss”)2019-11-29T09:11:32DateTime.Now.ToString(“HH:mm”)09:11DateTime.Now.ToString(“hh:mmtt”)09:11AMDateTime.Now.ToString(“H:mm”)9:11DateTime.Now.ToString(“h:mmtt”)9:11AMDateTime.Now.ToString(“HH:mm:ss”)09:11:32DateTime.Now.ToString(“yyyyMMMM”)2019NovemberDateTime.Now.ToString(“yyyyMMM”)2019NovDateTime.Now.ToString(“MM.dd.yyyyHH:mm”)11.29.201909:11DateTime.Now.ToString(“MM.dd.yyyyhh:mmtt”)11.29.201909:11AMDateTime.Now.ToString(“MM-dd-yyyyH:mm”)11-29-20199:11DateTime.Now.ToString(“MM-dd-yyyyh:mmtt”)11-29-20199:11AMDateTime.Now.ToString(“MM.dd.yyyyHH:mm:ss”)11.29.20199:11:32DateTime.Now.ToString(“dd/MM/yyyy”)29/11/2019 LetshavealookatbelowsampleC#codethatusestheseC#datetimeformats. namespaceDateTimeFormat { classProgram { staticvoidMain(string[]args) { //dterpresentsDateTimeobject. //HereDateTimeisaStructintheSystemnamespace. //year,month,date,hour,minute,seconds DateTimedt=newDateTime(2016,03,07,11,06,25); Console.WriteLine("Date:"+dt.ToString()); //Datetimeindifferentformats Console.WriteLine("***Datetimeindifferentformats***"); Console.WriteLine(dt.ToString("dd/MM/yyyy")); Console.WriteLine(dt.ToString("dd-MM-yyyy")); Console.WriteLine(dt.ToString("MM/dd/yyyy")); Console.WriteLine(dt.ToString("MM-dd-yyyy")); Console.WriteLine(dt.ToString("dddd,ddMMMMyyyy")); Console.WriteLine(dt.ToString("dddd,ddMMMMyyyyHH:mm:ss")); Console.WriteLine(dt.ToString("yyyyMMddHHmmss")); Console.WriteLine(dt.ToString("HH:mm")); Console.WriteLine(dt.ToString("dd/MM/yyyyHH:mm")); Console.WriteLine(dt.ToString("HH:mm:ss")); Console.WriteLine(dt.ToString("dd/MM/yyyyHH:mm:ss")); Console.WriteLine(dt.ToString("hh:mmtt")); Console.WriteLine(dt.ToString("dd/MM/yyyyhh:mmtt")); Console.WriteLine(dt.ToString("H:mm")); Console.WriteLine(dt.ToString("dd/MM/yyyyH:mm")); Console.WriteLine(dt.ToString("h:mmtt")); Console.WriteLine(dt.ToString("MM/dd/yyyyh:mmtt")); Console.WriteLine(dt.ToString("MMMMdd")); Console.WriteLine(dt.ToString("yyyy-MM-ddHH:mm:ss.fffffffK")); Console.WriteLine(dt.ToString("ddd,ddMMMyyyHH:mm:ss'GMT'")); Console.WriteLine(dt.ToString("yyyy-MM-ddHH:mm:ss")); Console.WriteLine(dt.ToString("yyyyMMMM")); Console.ReadLine(); } } } Theoutputoftheaboveprogramwillbesomethinglikethis: ThefollowingtabledescribesvariousC#DateTimeformatsandtheirresults.HereweseeallthepatternsoftheC#DateTimeformat,andresults. ForFormatResultNotes Day%d7Representsthedayofthemonthasanumbertom1through31. dd07Representsthedayofthemonthasanumberfrom01through31. dddMonRepresentstheabbreviatednameoftheday(MonTuesetc.). ddddMondayRepresentsthefullnameoftheday(Monday,Tuesday,etc.) Year%y11Representstheyearasanumberfrom1through99. yy11Representstheyearasanumberfrom01through99. yyyy2016Representstheyear(2011,2012,etc.) Month%M3RepresentstheMonthnumber(e.g.3,4,etc.) MM03RepresentstheMonthnumber(e.g.03,04,etc.) MMMMarRepresentstheabbreviatedMonthname(e.g.Mar,Apr,etc.) MMMMMarchRepresentsthefullMonthname(e.g.March,April,etc.) Hour(8PM)%h8Representsthe12-hourclockhour(e.g.8,9,etc.) hh08Representsthe12-hourclock,withleading0(e.g.08,09,etc.) HH20Representsthe24-hourclockhour,withleading0(e.g.22) Minutes%m6Minutes mm06Minuteswithleadingzero Secondss25Seconds ss25Secondswithleadingzero AMPMttAMAM/PM TimeZonezzz+5:30Representsthetimezone(e.g.+05.30) WhatIsSleepMethod? Thesleepmethodisusedtopausetherunningthreadforaspecifictimespan.Itacceptstimeinmilliseconds.Sleepisveryusefulinamulti-threadingenvironmentwhereyouwantonethreadtostoptomakewayforotherthreadstocompletetheirexecution. Syntax System.Threading.Thread.Sleep(1000); Conclusion Inthisarticle,wehavelearnedaboutDateTimeclass.ADateTimeobjectisusedtogatherinformationaboutthedateandtimeofthesystemortosetacustomdateandtimeforuseforaparticularapplicationrequirement. DateandTimeinC#arehandledbyDateTimeclassinC#thatprovidespropertiesandmethodstoformatdatesindifferentC#DateTimeformats. WealsolearnedaboutSleepmethod,itisthepartofSystem.Threadingandisusedtopausetheexecutionforacertaintimeinterval.Thisallowstheprogrammerstostartanotherthreadinthemulti-threadingenvironmentwhilethepreviousthreadispaused. RecommendedReading=>C#ExtensionMethodsExceptionHandlinginC#Top30.NetInterviewQuestionsAndAnswersUIPathInterviewQuestionsIntroductionToDotNetFrameworkGarbagecollectioninC# LeaveaCommentCancelreplyCommentName Email Website Savemyname,email,andwebsiteinthisbrowserforthenexttimeIcomment. Δ Searchfor: RecentPosts UIPathTutorial UIPathInterviewQuestions BluePrismInterviewQuestionsandAnswers Archives February2022 January2022 December2021 March2021 July2020 May2020 April2020 Weusecookiesonourwebsitetogiveyouthemostrelevantexperiencebyrememberingyourpreferencesandrepeatvisits.Byclicking“Accept”,youconsenttotheuseofALLthecookies.Donotsellmypersonalinformation.CookiesettingsACCEPTPrivacy&CookiesPolicy Close PrivacyOverview Thiswebsiteusescookiestoimproveyourexperiencewhileyounavigatethroughthewebsite.Outofthesecookies,thecookiesthatarecategorizedasnecessaryarestoredonyourbrowserastheyareessentialfortheworkingofbasicfunctionalitiesofthewebsite.Wealsousethird-partycookiesthathelpusanalyzeandunderstandhowyouusethiswebsite.Thesecookieswillbestoredinyourbrowseronlywithyourconsent.Youalsohavetheoptiontoopt-outofthesecookies.Butoptingoutofsomeofthesecookiesmayhaveaneffectonyourbrowsingexperience. Necessary Necessary AlwaysEnabled Necessarycookiesareabsolutelyessentialforthewebsitetofunctionproperly.Thiscategoryonlyincludescookiesthatensuresbasicfunctionalitiesandsecurityfeaturesofthewebsite.Thesecookiesdonotstoreanypersonalinformation. Non-necessary Non-necessary Anycookiesthatmaynotbeparticularlynecessaryforthewebsitetofunctionandisusedspecificallytocollectuserpersonaldataviaanalytics,ads,otherembeddedcontentsaretermedasnon-necessarycookies.Itismandatorytoprocureuserconsentpriortorunningthesecookiesonyourwebsite. SAVE&ACCEPT



請為這篇文章評分?