Working with Date and Time in C# - TutorialsTeacher

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

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=dt2);//False Console.WriteLine(dt1<=dt2);//True Tryit ConvertStringtoDateTime AvaliddateandtimestringcanbeconvertedtoaDateTimeobjectusingParse(),ParseExact(), TryParse()andTryParseExact()methods. TheParse()andParseExact()methodswillthrowanexceptionifthespecifiedstringisnotavalidrepresentationofadateandtime.So,it'srecommendedtouseTryParse()orTryParseExact()methodbecausetheyreturnfalseifastringisnotvalid. Example: varstr="5/12/2020"; DateTimedt; varisValidDate=DateTime.TryParse(str,outdt); if(isValidDate) Console.WriteLine(dt); else Console.WriteLine($"{str}isnotavaliddatestring"); Tryit Share Tweet Share Whatsapp LearnC#usingcodingquestionswithanswersandexplanations. C#Questions&Answers WanttocheckhowmuchyouknowC#? StartC#SkillTest RelatedArticles Asynchronousprogrammingwithasync,await,TaskinC# HowtoloopthroughanenuminC#? GenerateRandomNumbersinC# DifferencebetweenTwoDatesinC# ConvertinttoenuminC# BigIntegerDataTypeinC# ConvertStringtoEnuminC# ConvertanObjecttoJSONinC# ConvertJSONStringtoObjectinC# DateTimeFormatsinC# HowtoconvertdateobjecttostringinC#? ComparestringsinC# HowtocountelementsinC#array? DifferencebetweenStringandstringinC#. HowtogetacommaseparatedstringfromanarrayinC#? BoxingandUnboxinginC# HowtoconvertstringtointinC#? MoreC#articles Previous Next C#Questions&Answers C#SkillTest C#LatestArticles



請為這篇文章評分?