logo

DateTime i C#

Vi använde DateTime när det finns ett behov av att arbeta med datum och tider i C#.

Vi kan formatera datum och tid i olika format med egenskaperna och metoderna för DateTime./p>

Värdet på DateTime är mellan 12:00:00 midnatt, 1 januari 0001 och 23:59:59, 31 december 9999 A.D.

Här kommer vi att förklara hur man skapar DateTime i C#.

Vi har olika sätt att skapa DateTime-objektet. Ett DateTime-objekt har tid, kultur, datum, lokalisering, millisekunder.

Här har vi en kod som visar de olika konstruktoranvändningarna av DateTime-strukturen för att skapa DateTime-objekten.

 // From DateTime create the Date and Time DateTime DOB= new DateTime(19, 56, 8, 12, 8, 12, 23); // From String creation of DateTime string DateString= '8/12/1956 7:10:24 AM'; DateTime dateFromString = DateTime.Parse(DateString, System.Globalization.CultureInfo.InvariantCulture); Console.WriteLine(dateFromString.ToString()); // Empty DateTime DateTime EmpDateTime= new DateTime(); // Just date DateTime OnlyDate= new DateTime(2002, 10, 18); // DateTime from Ticks DateTime OnlyTime= new DateTime(10000000); // Localization with DateTime DateTime DateTimewithKind = new DateTime(1976, 7, 10, 7, 10, 24, DateTimeKind.Local); // DateTime with date, time and milliseconds DateTime WithMilliseconds= new DateTime(2010, 12, 15, 5, 30, 45, 100); 

Egenskaper för DateTime i C#

DateTime har egenskapen Date and Time. Från DateTime kan vi hitta datum och tid. DateTime innehåller också andra egenskaper, som timme, minut, sekund, millisekund, år, månad och dag.

De andra egenskaperna för DateTime är:

  1. Vi kan få dagens namn från veckan med hjälp av DayOfWeek-egendomen.
  2. För att få en dag på året kommer vi att använda DayOfYear-egenskapen.
  3. För att få tid i en DateTime använder vi TimeOfDay-egenskapen.
  4. Today-egenskapen returnerar objektet för DateTime, som har dagens värde. Tidens värde är 12:00:00
  5. Nu-egenskapen returnerar DateTime-objektet, som har det aktuella datumet och tiden.
  6. Utc-egenskapen för DateTime kommer att returnera Coordinated Universal Time (UTC).
  7. Den ena bocken representerar Hundra nanosekunder i DateTime. Ticks-egenskapen för DateTime returnerar antalet markeringar i en DateTime.
  8. Egenskapen Kind returnerar värde där representationen av tid görs av instansen, vilket är baserat på lokal tid, Coordinated Universal Time (UTC). Den visar också det ospecificerade standardvärdet.

Här tar vi ett exempel på att använda egenskaperna för DateTime i C#-koden.

Exempel:

 using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp8 { class Program { static void Main(string[] args) { DateTime DateTimeProperty = new DateTime(1974, 7, 10, 7, 10, 24); Console.WriteLine('Day:{0}', DateTimeProperty.Day); Console.WriteLine('Month:{0}', DateTimeProperty.Month); Console.WriteLine('Year:{0}', DateTimeProperty.Year); Console.WriteLine('Hour:{0}', DateTimeProperty.Hour); Console.WriteLine('Minute:{0}', DateTimeProperty.Minute); Console.WriteLine('Second:{0}', DateTimeProperty.Second); Console.WriteLine('Millisecond:{0}', DateTimeProperty.Millisecond); Console.WriteLine('Day of Week:{0}', DateTimeProperty.DayOfWeek); Console.WriteLine('Day of Year: {0}', DateTimeProperty.DayOfYear); Console.WriteLine('Time of Day:{0}', DateTimeProperty.TimeOfDay); Console.WriteLine('Tick:{0}', DateTimeProperty.Ticks); Console.WriteLine('Kind:{0}', DateTimeProperty.Kind); } } } 

Produktion:

DateTime i C#

Addition och subtraktion av DateTime i C#

DateTime-strukturen tillhandahåller metoderna för att lägga till och subtrahera datum och tid till och från DateTime-objektet. Vi kan lägga till och subtrahera datumet i DateTime-strukturen till och från DateTime-objektet. För addition och subtraktion i DateTime använder vi TimeSpan-strukturen.

För addition och subtraktion kan vi använda Add and Subtract-metoden från DateTime-objektet. Först skapar vi TimeSpan med värdena för datum och tid där vi använder Addera och Subtrahera metoder.

Här skapar vi en kod som lägger till 3 och subtraherar de 30 dagarna från idag och visar dagen på konsolen.

 using System; using System. Collections; using System.Collections.Generic; using System. Linq; using System. Text; using System.Threading.Tasks; namespace ConsoleApp8 { class Program { static void Main(string[] args) { DateTime Day = DateTime.Now; TimeSpan Month = new System.TimeSpan(30, 0, 0, 0); DateTime aDayAfterAMonth = Day.Add(Month); DateTime aDayBeforeAMonth = Day.Subtract(Month); Console.WriteLine('{0:dddd}', aDayAfterAMonth); Console.WriteLine('{0:dddd}', aDayBeforeAMonth); } } } 

DateTime-strukturen innehåller metoderna för att lägga till år, dagar, timmar, minuter, sekunder.

För att lägga till de olika komponenterna till DateTime-objektet används Add-metoden .

 // To Add the Years and Days day.AddYears(2); day.AddDays(12); // Add Hours, Minutes, Seconds, Milliseconds, and Ticks Day.AddHours(4.25); day.AddMinutes(15); day.AddSeconds(45); day.AddMilliseconds(200); day.AddTicks(5000); 

DateTime innehåller inte subtrahera metoden. För att subtrahera komponenten i DateTime kommer vi endast att använda subtraheringsmetoden. Till exempel: om vi behöver subtrahera de 12 dagarna från DateTime, kan vi skapa ett annat objekt av DateTime- eller TimeSpan-objektet med 12 dagar. Nu kommer vi att subtrahera detta objekt från DateTime. Som alternativ till detta kan vi också använda minusoperatorn för att subtrahera DateTime eller TimeSpan från DateTime.

Nu kommer vi att skapa en kod genom vilken vi kan skapa objektet för DateTime och subtrahera ett annat DateTime och Object of TimeSpan. I kod visar vi subtraktionen av endast timmar, dagar eller andra komponenter från DateTime.

 DateTime DOB = new DateTime(2000, 10, 20, 12, 15, 45); DateTime SubtractDate = new DateTime(2000, 2, 6, 13, 5, 15); // Use the TimeSpan with 10 days, 2 hrs, 30 mins, 45 seconds, and 100 milliseconds TimeSpan ts = new TimeSpan(10, 2, 30, 45, 100); // Subtract the DateTime TimeSpan Different = DOB.Subtract(SubtractDate); Console.WriteLine(Different.ToString()); // Subtract the TimeSpan DateTime Different2 = DOB.Subtract(ts); Console.WriteLine(Different2.ToString()); // Subtract 10 Days by creating the object SubtractedDays DateTime SubtractedDays = new DateTime(DOB.Year, DOB.Month, DOB.Day - 10); Console.WriteLine(SubtractedDays.ToString()); // Subtract hours, minutes, and seconds with creating the object HoursMinutesSeconds DateTime HoursMinutesSeconds = new DateTime(DOB.Year, DOB.Month, DOB.Day, DOB.Hour - 1, DOB.Minute - 15, DOB.Second - 15); Console.WriteLine(HoursMinutesSeconds.ToString()); 

Sökning av dagarna i månaden

För att hitta antalet dagar i månaden använde vi statiken DaysInMonth metod. Denna sökmetod [] tar parametern i siffror från 1 till 12.

Här kommer vi att skriva en kod genom vilken vi kommer att ta reda på antalet dagar i en viss månad.

Här får vi reda på antalet dagar i februari 2020. Resultatet kommer att vara 28 dagar.

 int NumberOfDays = DateTime.DaysInMonth(2004, 2); Console.WriteLine(NumberOfDays); 

Med samma teknik kan vi ta reda på det totala antalet dagar på ett år. För det kommer vi att använda metoden DaysInYear.

 private int DaysInYear(int year) { int DaysIN= 0; for (int j = 1; j <= 12; j++) { daysin +="DateTime.DaysInMonth(year," j); } return daysin; < pre> <h2>Comparison of two DateTime in C#</h2> <p> <strong>The comparer</strong> static method is used to compare the object of the two datetime. If the objects of both <strong>DateTime</strong> is the same, then the result will be 0. If the first DateTime is earlier, then the result will be 0 else the first DateTime would be later.</p> <p> <strong>Now we will show the comparison of the two datetime objects in C#.</strong> </p> <pre> using System; using System. Collections; using System.Collections.Generic; using System. Linq; using System. Text; using System.Threading.Tasks; namespace ConsoleApp8 { class Program { static void Main(string[] args) { DateTime DateOfFirst = new DateTime(2002, 10, 22); DateTime DateOfSecond = new DateTime(2009, 8, 11); int result1 = DateTime.Compare(DateOfFirst, DateOfSecond); if (result1 <0) console.writeline('date of first is earlier'); else if (result1="=" 0) console.writeline('both dates are same'); later'); } < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/net-framework/10/datetime-c-2.webp" alt="DateTime in C#"> <h2>CompareTo Method</h2> <p>CompareTo method is used to compare the two dates. We will assign the DateTime or object in this method.</p> <p>To compare the two DateTime object, we used the CompareTo method. Below we have a C# code to compare the DateTime object.</p> <pre> using System; using System. Collections; using System.Collections.Generic; using System. Linq; using System. Text; using System.Threading.Tasks; namespace ConsoleApp8 { class Program { static void Main(string[] args) { DateTime DateOfFirst = new DateTime(2001, 10, 20); DateTime DateOfSecond = new DateTime(2009, 8, 11); int ResultOfComparison = DateOfFirst.CompareTo(DateOfSecond); if (ResultOfComparison <0) console.writeline('date of first is earlier'); else if (resultofcomparison="=" 0) both are same'); later'); } < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/net-framework/10/datetime-c-3.webp" alt="DateTime in C#"> <h2>Formatting of the DateTime in C#</h2> <p>In C#, we can format the DateTime to any type of string format as we want.</p> <p>For the formatting of the DateTime, we used the <strong>GetDateTimeFormats</strong> method, which returns all the possible DateTime formats for the current culture of the computer.</p> <p>Here we have a C# code that returns the array of the strings of all the possible standard formats.</p> <pre> using System; using System. Collections; using System.Collections.Generic; using System. Linq; using System. Text; using System.Threading.Tasks; namespace ConsoleApp8 { class Program { static void Main(string[] args) { DateTime DateOfMonth = new DateTime(2020, 02, 25); string[] FormatsOfDate = DateOfMonth.GetDateTimeFormats(); foreach (string format in FormatsOfDate) Console.WriteLine(format); } } } </pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/net-framework/10/datetime-c-4.webp" alt="DateTime in C#"> <br> <img src="//techcodeview.com/img/net-framework/10/datetime-c-5.webp" alt="DateTime in C#"> <p>We can overload the <strong>GetDateTimeFormats</strong> method, which takes the format specifier as a parameter and converts the DateTime to that format. To get the desired format, we need to understand the format of the <strong>DateTime</strong> specifiers.</p> <p>We will show it with the code with the pattern in a table.</p> <table class="table"> <tr> <th>Code</th> <th>Pattern</th> </tr> <tr> <td>&apos;d&apos;</td> <td>Short date</td> </tr> <tr> <td>&apos;D&apos;</td> <td>Long date</td> </tr> <tr> <td>&apos;f&apos;</td> <td>Full date time. Short time.</td> </tr> <tr> <td>&apos;F&apos;</td> <td>Full date time. Long Time.</td> </tr> <tr> <td>&apos;g&apos;</td> <td>Generate date time. Long Time.</td> </tr> <tr> <td>&apos;G&apos;</td> <td>General date time. Long Time.</td> </tr> <tr> <td>&apos;M&apos;,&apos;m.&apos;</td> <td>Month/day</td> </tr> <tr> <td>&apos;O&apos;,&apos;o&apos;</td> <td>Round trip date/time.</td> </tr> <tr> <td>&apos;R&apos;,&apos;r&apos;</td> <td>RFC1123</td> </tr> <tr> <td>&apos;s&apos;</td> <td>Sortable date time.</td> </tr> <tr> <td>&apos;t&apos;</td> <td>Sort Time</td> </tr> <tr> <td>&apos;T&apos;</td> <td>Long Time</td> </tr> <tr> <td>&apos;u&apos;</td> <td>Universal sortable date time.</td> </tr> <tr> <td>&apos;U&apos;</td> <td>Universal full date-time.</td> </tr> <tr> <td>&apos;Y&apos;,&apos;y&apos;</td> <td>Year, Month</td> </tr> </table> <p> <strong>We will specify the format of the DateTime in the below C# Code. </strong> </p> <pre> using System; using System. Collections; using System.Collections.Generic; using System. Linq; using System. Text; using System.Threading.Tasks; namespace ConsoleApp8 { class Program { static void Main(string[] args) { DateTime FormatOfDate = new DateTime(2020, 02, 25); // DateTime Formats: d, D, f, F, g, G, m, o, r, s, t, T, u, U, Console.WriteLine(&apos;----------------&apos;); Console.WriteLine(&apos;d Formats&apos;); Console.WriteLine(&apos;----------------&apos;); string[] DateFormat = FormatOfDate.GetDateTimeFormats(&apos;d&apos;); foreach (string format in DateFormat) Console.WriteLine(format); Console.WriteLine(&apos;----------------&apos;); Console.WriteLine(&apos;D Formats&apos;); Console.WriteLine(&apos;----------------&apos;); DateFormat = FormatOfDate.GetDateTimeFormats(&apos;D&apos;); foreach (string format in DateFormat) Console.WriteLine(format); Console.WriteLine(&apos;----------------&apos;); Console.WriteLine(&apos;f Formats&apos;); Console.WriteLine(&apos;----------------&apos;); DateFormat = FormatOfDate.GetDateTimeFormats(&apos;f&apos;); foreach (string format in DateFormat) Console.WriteLine(format); Console.WriteLine(&apos;----------------&apos;); Console.WriteLine(&apos;F Formats&apos;); Console.WriteLine(&apos;----------------&apos;); DateFormat = FormatOfDate.GetDateTimeFormats(&apos;F&apos;); foreach (string format in DateFormat) Console.WriteLine(format); } } } </pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/net-framework/10/datetime-c-6.webp" alt="DateTime in C#"> <br> <img src="//techcodeview.com/img/net-framework/10/datetime-c-7.webp" alt="DateTime in C#"> <p>We can also do the formatting of the DateTime by passing the format specifier in the ToString() method of DateTime. Now we will write the C# code for the formatting of the DateTime using the ToString() method.</p> <pre> Console.WriteLine(DateOfFormat.ToString(&apos;r&apos;)); </pre> <p>Now we will write a C# code for the DateTime format specifiers within the ToString() method.</p> <img src="//techcodeview.com/img/net-framework/10/datetime-c-8.webp" alt="DateTime in C#"> <h2>Get the Leap Year and Daylight-Saving Time</h2> <p>Through the C# Code, we will get the Leap Year and Daylight-Saving Time.</p> <pre> using System; using System. Collections; using System.Collections.Generic; using System. Linq; using System. Text; using System.Threading.Tasks; namespace ConsoleApp8 { class Program { static void Main(string[] args) { DateTime DateOfTime = new DateTime(2020, 02, 22); Console.WriteLine(DateOfTime.IsDaylightSavingTime()); Console.WriteLine(DateTime.IsLeapYear(DateOfTime.Year)); } } } </pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/net-framework/10/datetime-c-9.webp" alt="DateTime in C#"> <h2>Conversion of string to the DateTime</h2> <p>To convert the string to a DateTime object, we used the Parse method. In the Parse method, the passing string must have the correct format of the DateTime. For the conversion of the DateTime to the String, the ToString() method is used. </p> <pre> using System; using System. Collections; using System.Collections.Generic; using System. Linq; using System. Text; using System.Threading.Tasks; namespace ConsoleApp8 { class Program { static void Main(string[] args) { string DT = &apos;2020-02-04T20:12:45-5:00&apos;; DateTime NEWDt = DateTime.Parse(DT); Console.WriteLine(NEWDt.ToString()); } } } </pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/net-framework/10/datetime-c-10.webp" alt="DateTime in C#"> <h2>Conversion of DateTime in C#</h2> <p>The structure of the DateTime is full of self-explanatory conversion, which converts the DateTime to the specific type. The methods are ToFileTime, ToLocalTime, ToLongDateString, ToBinary ,ToLongTimeString, ToOADate, ToShortDateString, ToShortTimeString, ToString, and ToUniversalTime.</p> <p>Here we will take an example of C# to convert the DateTime to the specific type.</p> <pre> using System; using System. Collections; using System.Collections.Generic; using System. Linq; using System. Text; using System.Threading.Tasks; namespace ConsoleApp8 { class Program { static void Main(string[] args) { DateTime DOB = new DateTime(2020, 01, 22); Console.WriteLine(&apos;ToString: &apos; + DOB.ToString()); Console.WriteLine(&apos;ToBinary: &apos; + DOB.ToBinary()); Console.WriteLine(&apos;ToFileTime: &apos; + DOB.ToFileTime()); Console.WriteLine(&apos;ToLocalTime: &apos; + DOB.ToLocalTime()); Console.WriteLine(&apos;ToLongDateString: &apos; + DOB.ToLongDateString()); Console.WriteLine(&apos;ToLongTimeString: &apos; + DOB.ToLongTimeString()); Console.WriteLine(&apos;ToOADate: &apos; + DOB.ToOADate()); Console.WriteLine(&apos;ToShortDateString: &apos; + DOB.ToShortDateString()); Console.WriteLine(&apos;ToShortTimeString: &apos; + DOB.ToShortTimeString()); Console.WriteLine(&apos;ToUniversalTime: &apos; + DOB.ToUniversalTime()); } } } </pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/net-framework/10/datetime-c-11.webp" alt="DateTime in C#"> <hr></0)></pre></0)></pre></=>

Produktion:

DateTime i C#
DateTime i C#

Vi kan överbelasta GetDateTimeFormats metod, som tar formatspecifikationen som en parameter och konverterar DateTime till det formatet. För att få det önskade formatet måste vi förstå formatet på Datum Tid specifikationer.

Vi kommer att visa det med koden med mönstret i en tabell.

Koda Mönster
'd' Kort dejt
'D' Lång dejt
'f' Full datum tid. Kort tid.
'F' Full datum tid. Länge sedan.
'g' Skapa datum och tid. Länge sedan.
'G' Allmänt datum tid. Länge sedan.
'M', 'm.' Månad dag
'O', 'o' Datum/tid för tur och retur.
'R','r' RFC1123
's' Sorterbar datum tid.
't' Sorteringstid
'T' Länge sedan
'i' Universell sorterbar datumtid.
'I' Universell full datum-tid.
'Och ​​och' År månad

Vi kommer att specificera formatet för DateTime i C#-koden nedan.

 using System; using System. Collections; using System.Collections.Generic; using System. Linq; using System. Text; using System.Threading.Tasks; namespace ConsoleApp8 { class Program { static void Main(string[] args) { DateTime FormatOfDate = new DateTime(2020, 02, 25); // DateTime Formats: d, D, f, F, g, G, m, o, r, s, t, T, u, U, Console.WriteLine(&apos;----------------&apos;); Console.WriteLine(&apos;d Formats&apos;); Console.WriteLine(&apos;----------------&apos;); string[] DateFormat = FormatOfDate.GetDateTimeFormats(&apos;d&apos;); foreach (string format in DateFormat) Console.WriteLine(format); Console.WriteLine(&apos;----------------&apos;); Console.WriteLine(&apos;D Formats&apos;); Console.WriteLine(&apos;----------------&apos;); DateFormat = FormatOfDate.GetDateTimeFormats(&apos;D&apos;); foreach (string format in DateFormat) Console.WriteLine(format); Console.WriteLine(&apos;----------------&apos;); Console.WriteLine(&apos;f Formats&apos;); Console.WriteLine(&apos;----------------&apos;); DateFormat = FormatOfDate.GetDateTimeFormats(&apos;f&apos;); foreach (string format in DateFormat) Console.WriteLine(format); Console.WriteLine(&apos;----------------&apos;); Console.WriteLine(&apos;F Formats&apos;); Console.WriteLine(&apos;----------------&apos;); DateFormat = FormatOfDate.GetDateTimeFormats(&apos;F&apos;); foreach (string format in DateFormat) Console.WriteLine(format); } } } 

Produktion:

schakal vs varg
DateTime i C#
DateTime i C#

Vi kan också formatera DateTime genom att skicka formatspecifikationen i ToString()-metoden för DateTime. Nu kommer vi att skriva C#-koden för formateringen av DateTime med ToString()-metoden.

 Console.WriteLine(DateOfFormat.ToString(&apos;r&apos;)); 

Nu kommer vi att skriva en C#-kod för DateTime-formatspecifikationerna inom ToString()-metoden.

DateTime i C#

Få skottår och sommartid

Genom C#-koden får vi skottår och sommartid.

 using System; using System. Collections; using System.Collections.Generic; using System. Linq; using System. Text; using System.Threading.Tasks; namespace ConsoleApp8 { class Program { static void Main(string[] args) { DateTime DateOfTime = new DateTime(2020, 02, 22); Console.WriteLine(DateOfTime.IsDaylightSavingTime()); Console.WriteLine(DateTime.IsLeapYear(DateOfTime.Year)); } } } 

Produktion:

DateTime i C#

Konvertering av sträng till DateTime

För att konvertera strängen till ett DateTime-objekt använde vi Parse-metoden. I Parse-metoden måste den passerande strängen ha rätt format för DateTime. För konverteringen av DateTime till String, används ToString()-metoden.

 using System; using System. Collections; using System.Collections.Generic; using System. Linq; using System. Text; using System.Threading.Tasks; namespace ConsoleApp8 { class Program { static void Main(string[] args) { string DT = &apos;2020-02-04T20:12:45-5:00&apos;; DateTime NEWDt = DateTime.Parse(DT); Console.WriteLine(NEWDt.ToString()); } } } 

Produktion:

DateTime i C#

Konvertering av DateTime i C#

Strukturen för DateTime är full av självförklarande konvertering, som konverterar DateTime till den specifika typen. Metoderna är ToFileTime, ToLocalTime, ToLongDateString, ToBinary ,ToLongTimeString, ToOADate, ToShortDateString, ToShortTimeString, ToString och ToUniversalTime.

Här tar vi ett exempel på C# för att konvertera DateTime till den specifika typen.

 using System; using System. Collections; using System.Collections.Generic; using System. Linq; using System. Text; using System.Threading.Tasks; namespace ConsoleApp8 { class Program { static void Main(string[] args) { DateTime DOB = new DateTime(2020, 01, 22); Console.WriteLine(&apos;ToString: &apos; + DOB.ToString()); Console.WriteLine(&apos;ToBinary: &apos; + DOB.ToBinary()); Console.WriteLine(&apos;ToFileTime: &apos; + DOB.ToFileTime()); Console.WriteLine(&apos;ToLocalTime: &apos; + DOB.ToLocalTime()); Console.WriteLine(&apos;ToLongDateString: &apos; + DOB.ToLongDateString()); Console.WriteLine(&apos;ToLongTimeString: &apos; + DOB.ToLongTimeString()); Console.WriteLine(&apos;ToOADate: &apos; + DOB.ToOADate()); Console.WriteLine(&apos;ToShortDateString: &apos; + DOB.ToShortDateString()); Console.WriteLine(&apos;ToShortTimeString: &apos; + DOB.ToShortTimeString()); Console.WriteLine(&apos;ToUniversalTime: &apos; + DOB.ToUniversalTime()); } } } 

Produktion:

DateTime i C#