Date and time in C# - working with date and time in CSharp
文章推薦指數: 80 %
In our first example, we get today's date. Program.cs. DateTime now = DateTime.Now; Console.WriteLine(now.ToString("F"));. The ... Ebooks PyQt5ebook Tkinterebook SQLitePython wxPythonebook WindowsAPIebook JavaSwingebook Javagamesebook MySQLJavaebook DateandtimeinC# lastmodifiedDecember3,2021 Inthistutorial,weshowhowtoworkwithdateandtimeinC#.C#tutorial isacomprehensivetutorialonC#language. C#DateTime TheDateTimevaluetyperepresentsdatesandtimeswithvalues rangingfrom00:00:00(midnight),January1,0001AnnoDomini(CommonEra) through11:59:59P.M.,December31,9999A.D.(C.E.)intheGregoriancalendar. C#TimeSpan TimeSpanrepresentsatimeinterval(durationoftimeorelapsed time)thatismeasuredasapositiveornegativenumberofdays,hours,minutes, seconds,andfractionsofasecond.TimeZoneInfoprovidestimezone informationandtoolstoworkwithdifferenttimezones. C#today'sdate Inourfirstexample,wegettoday'sdate. Program.cs DateTimenow=DateTime.Now; Console.WriteLine(now.ToString("F")); Theexampleprintstoday'sdate. DateTimenow=DateTime.Now; WiththeNowpropertyoftheDateTime,wegetthe currentdateandtimeinlocaltime. Console.WriteLine(now.ToString("F")); WiththeToStringmethod,weformatthedate.TheF specifiercreatesafulldateandtimepattern. $dotnetrun Friday,December3,20213:40:23PM C#DateTimeproperties DateTimerepresentsaninstantintime.Itspropertiesprovide variousaspectsofthedateandtime. Program.cs string[]months={"January","February","March","April","May", "June","July","August","September","October","November","December"}; DateTimenow=DateTime.Now; Console.WriteLine("Today'sdate:{0}",now.Date); Console.WriteLine("Todayis{0}dayof{1}",now.Day,months[now.Month-1]); Console.WriteLine("Todayis{0}dayof{1}",now.DayOfYear,now.Year); Console.WriteLine("Today'stime:{0}",now.TimeOfDay); Console.WriteLine("Hour:{0}",now.Hour); Console.WriteLine("Minute:{0}",now.Minute); Console.WriteLine("Second:{0}",now.Second); Console.WriteLine("Millisecond:{0}",now.Millisecond); Console.WriteLine("Thedayofweek:{0}",now.DayOfWeek); Console.WriteLine("Kind:{0}",now.Kind); TheexampleexaminesthepropertiesoftheDateTimeobject. DateTimenow=DateTime.Now; ADateTimeobjectiscreated.TheDateTimeissetto thecurrentlocaldateandtimeonthiscomputer. Console.WriteLine("Today'sdate:{0}",now.Date); TheDatepropertygetsthedatecomponentofthe DateTimeinstance. Console.WriteLine("Todayis{0}dayof{1}",now.Day,months[now.Month-1]); TheDaypropertygetsthedayofthemonth.TheMonth propertyreturnsthemonthcomponent,expressedasavaluebetween1and12. Console.WriteLine("Todayis{0}dayof{1}",now.DayOfYear,now.Year); TheDayOfYearpropertygetsthedayoftheyear,andthe Yeargetstheyear. Console.WriteLine("Today'stime:{0}",now.TimeOfDay); TheTimeOfDaypropertygetsthetimeofdayofthe DateTimeinstance. Console.WriteLine("Hour:{0}",now.Hour); Console.WriteLine("Minute:{0}",now.Minute); Console.WriteLine("Second:{0}",now.Second); Console.WriteLine("Millisecond:{0}",now.Millisecond); TheHour,Minute,Second,and Millisecondarepartsofthetimecomponent. Console.WriteLine("Thedayofweek:{0}",now.DayOfWeek); TheDayOfWeekpropertygetsthedayoftheweek. Console.WriteLine("Kind:{0}",now.Kind); TheKindpropertyreturnsavaluethatindicateswhetherthe timerepresentedbythisDateTimeinstanceisbasedonlocaltime, CoordinatedUniversalTime(UTC),orneither. $dotnetrun Today'sdate:12/3/202112:00:00AM Todayis3dayofDecember Todayis337dayof2021 Today'stime:15:41:38.0741142 Hour:15 Minute:41 Second:38 Millisecond:74 Thedayofweek:Friday Kind:Local C#addandsubtractDateTime DateTimehasmethodsfordoingtimearithmeticoperations. Program.cs DateTimedt=newDateTime(2019,2,22,14,0,0); DateTimedt1=dt.AddSeconds(55); DateTimedt2=dt.AddMinutes(30); DateTimedt3=dt.AddHours(72); DateTimedt4=dt.AddDays(65); DateTimedt5=dt.AddDays(-65); DateTimedt6=dt.AddMonths(3); DateTimedt7=dt.AddYears(4); Console.WriteLine(dt1.ToString("F")); Console.WriteLine(dt2.ToString("F")); Console.WriteLine(dt3.ToString("F")); Console.WriteLine(dt4.ToString("F")); Console.WriteLine(dt5.ToString("F")); Console.WriteLine(dt6.ToString("F")); Console.WriteLine(dt7.ToString("F")); TheexamplepresentssixmethodsoftheDateTimeobject. DateTimedt1=dt.AddSeconds(55); TheAddSecondsreturnsanewDateTimethat addsthespecifiednumberofsecondstothevalueofthisinstance. DateTimedt4=dt.AddDays(65); DateTimedt5=dt.AddDays(-65); TheAddDaysaddsdaystotheDateTime.Wecanprovide bothpositiveornegativevalues. $dotnetrun Friday,February22,20192:00:55PM Friday,February22,20192:30:00PM Monday,February25,20192:00:00PM Sunday,April28,20192:00:00PM Wednesday,December19,20182:00:00PM Wednesday,May22,20192:00:00PM Wednesday,February22,20232:00:00PM C#UTCtime Ourplanetisasphere;itrevolvesrounditsaxis.TheEarthrotatestowards theeast,sotheSunrisesatdifferenttimesindifferentlocations.TheEarth rotatesonceinabout24hours.Therefore,theworldwasdividedinto24time zones.Ineachtimezone,thereisadifferentlocaltime.Thislocaltimeis oftenfurthermodifiedbythedaylightsaving. Thereisapragmaticneedforoneglobaltime.Oneglobaltimehelpstoavoid confusionabouttimezonesanddaylightsavingtime.TheUTC(Universal Coordinatedtime)waschosentobetheprimarytimestandard.UTCisusedin aviation,weatherforecasts,flightplans,airtrafficcontrolclearances,and maps.Unlikelocaltime,UTCdoesnotchangewithachangeofseasons. Program.cs DateTimenow=DateTime.Now; DateTimeutc=DateTime.UtcNow; Console.WriteLine($"UTCtime{utc:HH:mm:ss}"); Console.WriteLine($"Localtime{now:HH:mm:ss}"); TheexampleprintsthecurrentUTCtimeandthelocaltime. DateTimeutc=DateTime.UtcNow; WiththeUtcNowpropertyoftheDateTime,weget theUTCtime. Console.WriteLine($"UTCtime{utc:HH:mm:ss}"); Weformatthetime. $dotnetrun UTCtime14:42:47 Localtime15:42:47 FortheCETtimezone,thereisonehourdifferenceintime. C#localizeddate TheDateTimeallowsustodisplaythedateandtimeinaspecific culture. Program.cs usingSystem.Globalization; Console.OutputEncoding=System.Text.Encoding.UTF8; DateTimenow=DateTime.Now; CultureInfoci=newCultureInfo("sk-SK"); Console.WriteLine($"Dnešnýdátumačas:{now.ToString("F",ci)}"); TheexampleprintsthecurrentdateandtimeinSlovakculture. Console.OutputEncoding=System.Text.Encoding.UTF8; TooutputtheaccentedSlovakcharacterscorrectly,wesetthe consoleoutputencodingtoUTF8. CultureInfoci=newCultureInfo("sk-SK"); WecreateaSlovakCultureInfo,whichincludesinformation aboutthenamesfortheculture,thewritingsystem,thecalendarused, thesortorderofstrings,andformattingfordatesandnumbers. Console.WriteLine($"Dnešnýdátumačas:{now.ToString("F",ci)}"); Weprintthedateandtimeinfulldateandtimeformatpattern. $dotnetrun Dnešnýdátumačas:piatok3.decembra202115:43:41 C#Unixtime TheUnixtimeisthenumberofsecondssincetheUnixepoch.TheUnixtimeis widelyusedincomputing.ThereisnomethodtogetUnixtimeinC#.Weneedto createourowncalculation. Program.cs longunixTime=DateTimeOffset.UtcNow.ToUnixTimeSeconds(); Console.WriteLine(unixTime); TheexampleprintstheUnixtime. longunixTime=DateTimeOffset.UtcNow.ToUnixTimeSeconds(); WegettheUnixtimewiththeToUnixTimeSecondsmethod. $dotnetrun 1638542651 Atthismoment,1638542651secondshavepassedsincetheUnix epoch. C#TimeSpan ATimeSpanstructurerepresentsatimeinterval. Program.cs stringstartTime="7:00AM"; stringendTime="8:30PM"; TimeSpanelapsed=DateTime.Parse(endTime).Subtract(DateTime.Parse(startTime)); Console.WriteLine($"Timeelapsed:{elapsed}"); Intheexample,wesubtracttwotimevalues. stringstartTime="7:00AM"; stringendTime="8:30PM"; Wedefinetwotimevaluesexpressedasstrings. TimeSpanelapsed=DateTime.Parse(endTime).Subtract(DateTime.Parse(startTime)); TheSubtractmethodisusedtosubtracttwotimevalues.The Parsemethodconvertsthestringrepresentationofatimeinterval toaTimeSpanobject. $dotnetrun Timeelapsed:13:30:00 Thedifferenceis13hoursand30minutes. Inthefollowingexample,wesubtracttwodatevalues. Program.cs DateTimenow=DateTime.Today; DateTimeborodino_battle=newDateTime(1812,9,7); TimeSpandiff=now-borodino_battle; Console.WriteLine($"{diff.TotalDays}dayshavepassedsincetheBattleofBorodino."); Intheexample,wecomputethenumberofdayspassedsincetheBorodinobattle. DateTimenow=DateTime.Today; DateTimeborodino_battle=newDateTime(1812,9,7); WedefinetwoDateTimeobjects:onefortodayandoneforthedate oftheBorodinobattle. TimeSpandiff=now-borodino_battle; Bysubtractingthosetwoobjects,wegetaTimeSpanobject. Console.WriteLine($"{diff.TotalDays}dayshavepassedsincetheBattleofBorodino."); TheTotalDayspropertyhasthenumberofdaysoftheelapsedtime. $dotnetrun 76423dayshavepassedsincetheBattleofBorodino. OnDecember3,2021,76423dayshavepassedsincetheBattleofBorodino. C#formattime AdateandtimeformatstringdefinesthetextrepresentationofaDateTime orDateTimeOffsetvaluethatresultsfromaformattingoperation. Therearetwotypesofformatspecifiers:standardandcustom.Acustomdateand timeformatstringconsistsoftwoormorecharacters. Program.cs DateTimenow=DateTime.Now; Console.WriteLine(now.ToString("d")); Console.WriteLine(now.ToString("D")); Console.WriteLine(now.ToString("F")); Console.WriteLine(now.ToString("M")); Console.WriteLine(now.ToString("o")); Console.WriteLine(now.ToString("R")); Console.WriteLine(now.ToString("t")); Console.WriteLine(now.ToString("T")); Console.WriteLine(now.ToString("Y")); Theexampleprintstoday'sdateusingsomeofthestandardformatspecifiers. Console.WriteLine(now.ToString("d")); Thedspecifiercreatesashortdatepattern. Console.WriteLine(now.ToString("D")); TheDspecifiercreatesalongdatepattern. Console.WriteLine(now.ToString("F")); TheFspecifiercreatesafulldateandtimepattern. Console.WriteLine(now.ToString("M")); TheMspecifiercreatesamonthanddaypattern. Console.WriteLine(now.ToString("o")); Theospecifiercreatesaround-tripdateandtimepattern. Inthispattern,thedateandtimepartsareseparatedbytheT characterandthetimezonebiasisappendedattheendofthestring. Console.WriteLine(now.ToString("R")); TheRspecifiercreatesanRFC1123dateandtimepattern. Console.WriteLine(now.ToString("t")); Thetspecifiercreatesashorttimepattern. Console.WriteLine(now.ToString("T")); Thetspecifiercreatesalongtimepattern. Console.WriteLine(now.ToString("Y")); TheYspecifiercreatesayearandmonthpattern. $dotnetrun 12/3/2021 Friday,December3,2021 Friday,December3,20213:45:31PM December3 2021-12-03T15:45:31.9734136+01:00 Fri,03Dec202115:45:31GMT 3:45PM 3:45:31PM December2021 Customformatspecifiersallowustocreatecustomizeddateandtimeformat patterns. Program.cs DateTimenow=DateTime.Now; Console.WriteLine(now.ToString("dddMMM%d,yyyy")); Console.WriteLine(now.ToString("hh:mm:sstt")); Theexampleprintsadateandatimeformatusingcustomspecifiers. Console.WriteLine(now.ToString("dddMMM%d,yyyy")); Thedddspecifieristheabbreviatednameof thedayoftheweek,theMMMisthe abbreviatednameofthemonth,thedisthedayof themonth,from1through31.Inthecontextofcustomspecifiers, itmustbeprecededwiththe%character.Finally, theyyyyistheyearasafour-digitnumber. Console.WriteLine(now.ToString("hh:mm:sstt")); Thehhspecifieristhehour,usinga12-hourclockfrom01to12, themmistheminute,from00through59,thessis thesecond,from00through59,andthettistheAM/PMdesignator. $dotnetrun FriDec3,2021 03:46:04PM C#parsetime TheDateTime'sParsemethodconvertsthestring representationofadateandtimetoitsDateTimeequivalent. Program.cs stringdate_string="11/5/2019"; DateTimedt=DateTime.Parse(date_string); Console.WriteLine($"{dt:dMMMM,yyyy}"); Theprogramparsesadateinastring. stringdate_string="11/5/2019"; Thisisadateexpressedinastring. DateTimedt=DateTime.Parse(date_string); WiththeParsemethod,weparseitintotheDateTime object. Console.WriteLine($"{dt:dMMMM,yyyy}"); Thedateisprintedtotheconsoleinamiddle-endianorder. $dotnetrun 5November,2019 C#Timezones Atimezoneisaregionthroughoutwhichthesamestandardtimeis used.Thereare24timezonesintheworld. UTC=localtime+bias ThebiasisthedifferencebetweenUTCtimeandlocaltime. TimeZoneInfoisaclassforworkingwithtimezonesinC#. Program.cs TimeZoneInfolocalZone=TimeZoneInfo.Local; Console.WriteLine("Currenttimezone:{0}",localZone.StandardName); Console.WriteLine("Daylightname:{0}",localZone.DaylightName); Console.WriteLine("Bias:{0}",localZone.BaseUtcOffset); Theprogramprintsthecurrenttimezoneandthebias. TimeZoneInfolocalZone=TimeZoneInfo.Local; UsingtheLocalproperty,wegetthelocaltimezone. Console.WriteLine("Currenttimezone:{0}",localZone.StandardName); Console.WriteLine("Daylightname:{0}",localZone.DaylightName); TheStandardNamegivesthetimezone'sstandardnameandthe DaylightNameitsdaylightsavingname. Console.WriteLine("Bias:{0}",localZone.BaseUtcOffset); TheBaseUtcOffsetpropertyproducesthebias. $dotnetrun Currenttimezone:CentralEuropeanStandardTime Daylightname:CentralEuropeanSummerTime Bias:01:00:00 OnasystemlocatedinBratislava,wegetthesevalues. TheGetSystemTimeZonesmethodreturnsasortedcollectionofall thetimezonesaboutwhichinformationisavailableonthelocalsystem. Program.cs vartimezones=TimeZoneInfo.GetSystemTimeZones(); foreach(vartimezoneintimezones) { Console.WriteLine(timezone.Id); } TheexampleprintstheIdsofavailabletimezonesonasystem. $dotnetrun ... NewfoundlandStandardTime TocantinsStandardTime E.SouthAmericaStandardTime SAEasternStandardTime ArgentinaStandardTime GreenlandStandardTime MontevideoStandardTime MagallanesStandardTime SaintPierreStandardTime BahiaStandardTime UTC-02 Mid-AtlanticStandardTime AzoresStandardTime CapeVerdeStandardTime UTC ... Thisisapartialoutputoftheprogram. TimezoneinformationcanalsoberetrievedfromaDateTimevalue withsomeformatspecifiers. Program.cs DateTimenow=DateTime.Now; Console.WriteLine(now.ToString("%z")); Console.WriteLine(now.ToString("%K")); Console.WriteLine(now.ToString("o")); Theexamplethelocaltimezone'sbiasusingformatspecifiers. $dotnetrun +1 +01:00 2021-12-03T15:46:53.4899637+01:00 C#Leapyear Aleapyearisayearcontaininganadditionalday.Thereasonforan extradayinthecalendaristhedifferencebetweentheastronomicalandthe calendaryear. Program.cs //Assumeyear>=1582intheGregoriancalendar. int[]years={2000,2002,2004,2008,2012,2016,2020, 1900,1800,1600}; foreach(intyearinyears) { if(DateTime.IsLeapYear(year)) { Console.WriteLine($"{year}isaleapyear"); }else { Console.WriteLine($"{year}isnotaleapyear"); } } Wehaveanarrayofyears.Wecheckallyearsiftheyareleapyearsornot. TheIsLeapYearfunctiondetermineswhetherayearisaleapyear. int[]years={2000,2002,2004,2008,2012,2016,2020, 1900,1800,1600}; Thisisanarrayofyearsthatwecheck.TheyearsmustbeintheGregorian calendar. foreach(intyearinyears) { if(DateTime.IsLeapYear(year)) { Console.WriteLine($"{year}isaleapyear"); } else { Console.WriteLine($"{year}isnotaleapyear"); } } Withtheforloopwetraversethearray.Wecheckifayearisaleapyearusing theIsLeapYearfunction. $dotnetrun 2000isaleapyear 2002isnotaleapyear 2004isaleapyear 2008isaleapyear 2012isaleapyear 2016isaleapyear 2020isaleapyear 1900isnotaleapyear 1800isnotaleapyear 1600isaleapyear Inthisarticle,wehaveworkedwithdateandtimeinC#. ReadC#tutorialorlistallC#tutorials.
延伸文章資訊
- 1【C#】《DateTime》獲取時間到毫秒的方式(今天、昨天、明天
說明: 來看看C#獲取時間到毫秒的方式(今天、昨天、明天、日期比大小) /*獲取今天日期(只有日期)*/DateTime GetNowDate = DateTime.Today; Outp.
- 2C# DateTime.Today (Current Day With Zero Time) - Dot Net ...
DateTime.Today returns just the day—without the time. This is different from DateTime.Now, which ...
- 3Difference between DateTime.Today and ... - NET Fiddle
Difference between DateTime.Today and DateTime.Now | Test your C# code online with .NET Fiddle co...
- 4How do I get today's date in C# in mm/dd/yyyy format? - Stack ...
string today = DateTime.Today.ToString("M/d");.
- 5Date and time in C# - working with date and time in CSharp
In our first example, we get today's date. Program.cs. DateTime now = DateTime.Now; Console.Write...