Working with Date and Time in C# - TutorialsTeacher
文章推薦指數: 80 %
C# includes DateTime struct to work with dates and times. To work with date and ... Today; // returns today's date DateTime currentDateTimeUTC = DateTime.
C#
ASP.NETCore
MVC
IoC
TypeScript
Angular
Python
SQLServer
MongoDB
More
✕
.NETTutorials
C#
ASP.NETCore
ASP.NETMVC
IoC
webapi
LINQ
ClientSide
JavaScript
jQuery
Node.js
D3.js
TypeScript
Angular11
AngularJS1
Sass
ServerSide
https
Python
SQL
SQLServer
PostgreSQL
MongoDB
SkillTests
ASP.NETCore
ASP.NETMVC
LINQ
C#
webapi
IoC
TypeScript
AngularJS
Node.js
jQuery
JavaScript
Articles
Tests
LearnC#
C#-GetStarted
C#-VersionHistory
C#-FirstProgram
C#-Keywords
C#-Class
C#-Variable
C#-Implicitly-TypedVariable
C#-DataTypes
Numbers
Strings
DateTime
Structure
Enum
StringBuilder
AnonymousTypes
DynamicTypes
NullableTypes
C#-Value&ReferenceTypes
C#-Interface
C#-Operators
C#-ifelseStatements
C#-TernaryOperator?:
C#-Switch
C#-ForLoop
C#-WhileLoop
C#-Do-whileLoop
C#-PartialClass
C#-Static
C#-Array
MultidimensionalArray
JaggedArray
C#-Indexer
C#-Generics
GenericConstraints
C#-Collections
ArrayList
List
SortedList
Dictionary
Hashtable
Stack
Queue
C#-Tuple
C#-ValueTuple
C#-Built-inExceptions
ExceptionHandling
throw
CustomException
C#-Delegates
FuncDelegate
ActionDelegate
PredicateDelegate
AnonymousMethods
C#-Events
C#-Covariance
C#-ExtensionMethod
C#-StreamI/O
C#-File
C#-FileInfo
C#-ObjectInitializer
C#-UsefulResources
Previous
Next
WorkingwithDateandTimeinC#
C#includesDateTimestructtoworkwithdatesandtimes.
ToworkwithdateandtimeinC#,createanobjectoftheDateTimestructusingthenewkeyword.ThefollowingcreatesaDateTimeobjectwiththedefaultvalue.
Example:CreateDateTimeObject
DateTimedt=newDateTime();//assignsdefaultvalue01/01/000100:00:00
ThedefaultandthelowestvalueofaDateTimeobjectisJanuary1,000100:00:00(midnight).ThemaximumvaluecanbeDecember31,999911:59:59P.M.
UsedifferentconstructorsoftheDateTimestructtoassignaninitialvaluetoaDateTimeobject.
Example:SetDate&Time
//assignsdefaultvalue01/01/000100:00:00
DateTimedt1=newDateTime();
//assignsyear,month,day
DateTimedt2=newDateTime(2015,12,31);
//assignsyear,month,day,hour,min,seconds
DateTimedt3=newDateTime(2015,12,31,5,10,20);
//assignsyear,month,day,hour,min,seconds,UTCtimezone
DateTimedt4=newDateTime(2015,12,31,5,10,20,DateTimeKind.Utc);
Tryit
Intheaboveexample,wespecifiedayear,amonth,andadayintheconstructor.Theyearcanbefrom0001to9999,andtheMonthcanbefrom1to12,andthedaycanbefrom1to31.Settinganyothervalueoutoftheserangeswillresultinarun-timeexception.
Example:InvalidDate
DateTimedt=newDateTime(2015,12,32);//throwsexception:dayoutofrange
UsedifferentDateTimeconstructorstosetdate,time,timezone,calendar,andculture.
Ticks
Ticksisadateandtimeexpressedinthenumberof100-nanosecondintervalsthathaveelapsedsinceJanuary1,0001,at00:00:00.000intheGregoriancalendar.ThefollowinginitializesaDateTimeobjectwiththenumberofticks.
Example:Ticks
DateTimedt=newDateTime(636370000000000000);
DateTime.MinValue.Ticks;//minvalueofticks
DateTime.MaxValue.Ticks;//maxvalueofticks
Tryit
DateTimeStaticFields
TheDateTimestructincludesstaticfields,properties,andmethods.Thefollowingexampledemonstratesimportantstaticfieldsandproperties.
Example:StaticFields
DateTimecurrentDateTime=DateTime.Now;//returnscurrentdateandtime
DateTimetodaysDate=DateTime.Today;//returnstoday'sdate
DateTimecurrentDateTimeUTC=DateTime.UtcNow;//returnscurrentUTCdateandtime
DateTimemaxDateTimeValue=DateTime.MaxValue;//returnsmaxvalueofDateTime
DateTimeminDateTimeValue=DateTime.MinValue;//returnsminvalueofDateTime
Tryit
TimeSpan
TimeSpanisastructthatisusedtorepresenttimeindays,hour,minutes,seconds,andmilliseconds.
Example:TimeSpan
DateTimedt=newDateTime(2015,12,31);
TimeSpants=newTimeSpan(25,20,55);
DateTimenewDate=dt.Add(ts);
Console.WriteLine(newDate);//1/1/20161:20:55AM
Tryit
SubtractionoftwodatesresultsinTimeSpan.
Example:SubtractDates
DateTimedt1=newDateTime(2015,12,31);
DateTimedt2=newDateTime(2016,2,2);
TimeSpanresult=dt2.Subtract(dt1);//33.00:00:00
Tryit
Operators
TheDateTimestructoverloads+,-,==,!=,>,=operatorstoeaseoutaddition,subtraction,andcomparisonofdates.Thesemakeiteasytoworkwithdates.
Example:Operators
DateTimedt1=newDateTime(2015,12,20);
DateTimedt2=newDateTime(2016,12,31,5,10,20);
TimeSpantime=newTimeSpan(10,5,25,50);
Console.WriteLine(dt2+time);//1/10/201710:36:10AM
Console.WriteLine(dt2-dt1);//377.05:10:20
Console.WriteLine(dt1==dt2);//False
Console.WriteLine(dt1!=dt2);//True
Console.WriteLine(dt1>dt2);//False
Console.WriteLine(dt1
延伸文章資訊
- 1Date 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...
- 2Difference between DateTime.Today and ... - NET Fiddle
Difference between DateTime.Today and DateTime.Now | Test your C# code online with .NET Fiddle co...
- 3【C#】《DateTime》獲取時間到毫秒的方式(今天、昨天、明天
說明: 來看看C#獲取時間到毫秒的方式(今天、昨天、明天、日期比大小) /*獲取今天日期(只有日期)*/DateTime GetNowDate = DateTime.Today; Outp.
- 4DateTime.Today 屬性(System) | Microsoft Docs
DateTime thisDay = DateTime.Today; // Display the date in the default (general) format. Console.W...
- 5C# 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 ...