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
延伸文章資訊
- 1How do I get today's date in C# in mm/dd/yyyy format? - Stack ...
string today = DateTime.Today.ToString("M/d");.
- 2C# DateTime.Today屬性代碼示例- 純淨天空
C# DateTime.Today屬性代碼示例,System.DateTime.Today用法.
- 3Difference between DateTime.Today and ... - NET Fiddle
Difference between DateTime.Today and DateTime.Now | Test your C# code online with .NET Fiddle co...
- 4DateTime.Today 屬性(System) | Microsoft Docs
DateTime thisDay = DateTime.Today; // Display the date in the default (general) format. Console.W...
- 5C# DateTime Format:Working with Date &Time format in C#|
This blog describes how to format DateTime in C# with a code sample. ... We can easily convert it...