Koristili smo DateTime kada je trebalo raditi s datumima i vremenima u C#.
Datum i vrijeme možemo formatirati u različitim formatima pomoću svojstava i metoda DateTime./p>
Vrijednost DateTime je između 12:00:00 ponoći, 1. siječnja 0001. i 23:59:59 PM, 31. prosinca 9999. godine.
Ovdje ćemo objasniti kako stvoriti DateTime u C#.
Imamo različite načine za stvaranje objekta DateTime. Objekt DateTime ima vrijeme, kulturu, datum, lokalizaciju, milisekunde.
Ovdje imamo kod koji pokazuje razne konstruktore koje DateTime struktura koristi za stvaranje DateTime objekata.
// 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);
Svojstva datuma i vremena u C#
DateTime ima svojstvo Datum i vrijeme. Iz DateTime možemo pronaći datum i vrijeme. DateTime sadrži i druga svojstva, kao što su sat, minuta, sekunda, milisekunda, godina, mjesec i dan.
Ostala svojstva DateTime su:
- Možemo dobiti ime dana iz tjedna uz pomoć svojstva DayOfWeek.
- Da bismo dobili dan u godini, koristit ćemo svojstvo DayOfYear.
- Da bismo dobili vrijeme u DateTime, koristimo svojstvo TimeOfDay.
- Svojstvo Today vratit će objekt DateTime koji ima današnju vrijednost. Vrijednost vremena je 12:00:00
- Svojstvo Now vratit će objekt DateTime koji ima trenutni datum i vrijeme.
- Svojstvo Utc za DateTime vratit će koordinirano univerzalno vrijeme (UTC).
- Jedna kvačica predstavlja stotinu nanosekundi u DateTime. Svojstvo Ticks za DateTime vraća broj otkucaja u DateTime.
- Svojstvo Kind vraća vrijednost u kojoj se vrijeme prikazuje putem instance, koja se temelji na lokalnom vremenu, koordiniranom univerzalnom vremenu (UTC). Također prikazuje neodređenu zadanu vrijednost.
Ovdje uzimamo primjer korištenja svojstava DateTime u C# kodu.
Primjer:
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); } } }
Izlaz:
Zbrajanje i oduzimanje datuma i vremena u C#
Struktura DateTime pruža metode za dodavanje i oduzimanje datuma i vremena objektu DateTime. Datum u strukturi DateTime možemo dodavati i oduzimati objektu DateTime. Za zbrajanje i oduzimanje u DateTime koristimo strukturu TimeSpan.
Za zbrajanje i oduzimanje možemo koristiti metodu zbrajanja i oduzimanja iz objekta DateTime. Prvo, kreiramo TimeSpan s vrijednostima datuma i vremena gdje koristimo metode Add i Subtract.
Ovdje stvaramo kod koji će dodati 3 i oduzeti 30 dana od današnjeg dana i prikazati dan na konzoli.
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); } } }
Struktura DateTime sadrži metode za dodavanje godina, dana, sati, minuta, sekundi.
Za dodavanje različitih komponenti objektu DateTime koristi se metoda Add .
// 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 ne sadrži metodu oduzimanja. Za oduzimanje komponente DateTime koristit ćemo samo metodu oduzimanja. Na primjer: ako trebamo oduzeti 12 dana od DateTime, možemo stvoriti drugi objekt DateTime ili TimeSpan objekt s 12 dana. Sada ćemo oduzeti ovaj objekt od DateTime. Kao alternativa tome, također možemo koristiti operator minus da oduzmemo DateTime ili TimeSpan od DateTime.
Sada ćemo stvoriti kod pomoću kojeg možemo kreirati objekt DateTime i oduzeti drugi DateTime i Object od TimeSpan. U kodu ćemo prikazati oduzimanje samo sati, dana ili drugih komponenti od 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());
Traženje dana u mjesecu
Da bismo pronašli broj dana u mjesecu, koristili smo statiku Dani U Mjesecu metoda. Ova metoda pretraživanja [] uzima parametar u brojevima od 1 do 12.
Ovdje ćemo napisati šifru pomoću koje ćemo saznati broj dana u pojedinom mjesecu.
Ovdje ćemo saznati broj dana u veljači 2020. Izlaz će biti 28 dana.
int NumberOfDays = DateTime.DaysInMonth(2004, 2); Console.WriteLine(NumberOfDays);
Istom tehnikom možemo saznati ukupan broj dana u godini. Za to ćemo koristiti metodu 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>'d'</td> <td>Short date</td> </tr> <tr> <td>'D'</td> <td>Long date</td> </tr> <tr> <td>'f'</td> <td>Full date time. Short time.</td> </tr> <tr> <td>'F'</td> <td>Full date time. Long Time.</td> </tr> <tr> <td>'g'</td> <td>Generate date time. Long Time.</td> </tr> <tr> <td>'G'</td> <td>General date time. Long Time.</td> </tr> <tr> <td>'M','m.'</td> <td>Month/day</td> </tr> <tr> <td>'O','o'</td> <td>Round trip date/time.</td> </tr> <tr> <td>'R','r'</td> <td>RFC1123</td> </tr> <tr> <td>'s'</td> <td>Sortable date time.</td> </tr> <tr> <td>'t'</td> <td>Sort Time</td> </tr> <tr> <td>'T'</td> <td>Long Time</td> </tr> <tr> <td>'u'</td> <td>Universal sortable date time.</td> </tr> <tr> <td>'U'</td> <td>Universal full date-time.</td> </tr> <tr> <td>'Y','y'</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('----------------'); Console.WriteLine('d Formats'); Console.WriteLine('----------------'); string[] DateFormat = FormatOfDate.GetDateTimeFormats('d'); foreach (string format in DateFormat) Console.WriteLine(format); Console.WriteLine('----------------'); Console.WriteLine('D Formats'); Console.WriteLine('----------------'); DateFormat = FormatOfDate.GetDateTimeFormats('D'); foreach (string format in DateFormat) Console.WriteLine(format); Console.WriteLine('----------------'); Console.WriteLine('f Formats'); Console.WriteLine('----------------'); DateFormat = FormatOfDate.GetDateTimeFormats('f'); foreach (string format in DateFormat) Console.WriteLine(format); Console.WriteLine('----------------'); Console.WriteLine('F Formats'); Console.WriteLine('----------------'); DateFormat = FormatOfDate.GetDateTimeFormats('F'); 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('r')); </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 = '2020-02-04T20:12:45-5:00'; 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('ToString: ' + DOB.ToString()); Console.WriteLine('ToBinary: ' + DOB.ToBinary()); Console.WriteLine('ToFileTime: ' + DOB.ToFileTime()); Console.WriteLine('ToLocalTime: ' + DOB.ToLocalTime()); Console.WriteLine('ToLongDateString: ' + DOB.ToLongDateString()); Console.WriteLine('ToLongTimeString: ' + DOB.ToLongTimeString()); Console.WriteLine('ToOADate: ' + DOB.ToOADate()); Console.WriteLine('ToShortDateString: ' + DOB.ToShortDateString()); Console.WriteLine('ToShortTimeString: ' + DOB.ToShortTimeString()); Console.WriteLine('ToUniversalTime: ' + 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></=>
Izlaz:
Možemo preopteretiti GetDateTimeFormats metoda, koja uzima specifikator formata kao parametar i pretvara DateTime u taj format. Da bismo dobili željeni format, moramo razumjeti format Datum vrijeme specifikatori.
Prikazat ćemo to kodom s uzorkom u tablici.
Kodirati | Uzorak |
---|---|
'd' | Kratki spoj |
'D' | Dugi spoj |
'f' | Vrijeme punog datuma. Kratko vrijeme. |
'F' | Vrijeme punog datuma. Dugo vrijeme. |
'g' | Generiraj datum i vrijeme. Dugo vrijeme. |
'G' | Opći datum i vrijeme. Dugo vrijeme. |
'M','m.' | Mjesec dan |
'O', 'o' | Datum/vrijeme povratnog putovanja. |
'R','r' | RFC1123 |
's' | Datum i vrijeme koje se može sortirati. |
't' | Razvrstaj vrijeme |
'T' | Dugo vrijeme |
'u' | Univerzalni datum i vrijeme koji se može sortirati. |
'U' | Univerzalni puni datum-vrijeme. |
'I','i' | Godina, mjesec |
Navest ćemo format datuma i vremena u donjem C# kodu.
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('----------------'); Console.WriteLine('d Formats'); Console.WriteLine('----------------'); string[] DateFormat = FormatOfDate.GetDateTimeFormats('d'); foreach (string format in DateFormat) Console.WriteLine(format); Console.WriteLine('----------------'); Console.WriteLine('D Formats'); Console.WriteLine('----------------'); DateFormat = FormatOfDate.GetDateTimeFormats('D'); foreach (string format in DateFormat) Console.WriteLine(format); Console.WriteLine('----------------'); Console.WriteLine('f Formats'); Console.WriteLine('----------------'); DateFormat = FormatOfDate.GetDateTimeFormats('f'); foreach (string format in DateFormat) Console.WriteLine(format); Console.WriteLine('----------------'); Console.WriteLine('F Formats'); Console.WriteLine('----------------'); DateFormat = FormatOfDate.GetDateTimeFormats('F'); foreach (string format in DateFormat) Console.WriteLine(format); } } }
Izlaz:
jfx java vodič
Također možemo izvesti formatiranje DateTimea prosljeđivanjem specifikatora formata u metodi ToString() DateTimea. Sada ćemo napisati C# kod za formatiranje DateTime koristeći ToString() metodu.
Console.WriteLine(DateOfFormat.ToString('r'));
Sada ćemo napisati C# kod za specifikatore formata DateTime unutar metode ToString().
Dobijte prijestupnu godinu i ljetno računanje vremena
Preko C# koda dobit ćemo prijestupnu godinu i ljetno računanje vremena.
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)); } } }
Izlaz:
Pretvorba niza u datum i vrijeme
Za pretvaranje niza u objekt DateTime upotrijebili smo metodu Parse. U metodi Parse, prolazni niz mora imati ispravan format DateTime. Za konverziju DateTime u String koristi se metoda ToString().
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 = '2020-02-04T20:12:45-5:00'; DateTime NEWDt = DateTime.Parse(DT); Console.WriteLine(NEWDt.ToString()); } } }
Izlaz:
Konverzija DateTime u C#
Struktura DateTime puna je samoobjašnjive konverzije, koja pretvara DateTime u određeni tip. Metode su ToFileTime, ToLocalTime, ToLongDateString, ToBinary, ToLongTimeString, ToOADate, ToShortDateString, ToShortTimeString, ToString i ToUniversalTime.
Ovdje ćemo uzeti primjer C# kako bismo pretvorili DateTime u određeni tip.
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('ToString: ' + DOB.ToString()); Console.WriteLine('ToBinary: ' + DOB.ToBinary()); Console.WriteLine('ToFileTime: ' + DOB.ToFileTime()); Console.WriteLine('ToLocalTime: ' + DOB.ToLocalTime()); Console.WriteLine('ToLongDateString: ' + DOB.ToLongDateString()); Console.WriteLine('ToLongTimeString: ' + DOB.ToLongTimeString()); Console.WriteLine('ToOADate: ' + DOB.ToOADate()); Console.WriteLine('ToShortDateString: ' + DOB.ToShortDateString()); Console.WriteLine('ToShortTimeString: ' + DOB.ToShortTimeString()); Console.WriteLine('ToUniversalTime: ' + DOB.ToUniversalTime()); } } }
Izlaz:
0)>0)>=>