English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
C# includes the DateTime structure that can handle dates and times.
To use date and time in C#, use the new keyword to create an object of the DateTime structure. Below, create a DateTime object with a default value.
DateTime dt = new DateTime(); // Assign default value 01/01/0001 00:00:00
The default value and minimum value of DateTime objects are 0001Year1Month1Day 00:00:00 (midnight). The maximum value can be9999Year12Month31Night11:59:59
Use different constructors of the DateTime structure to assign initial values to DateTime objects.
//Assign default value 01/01/0001 00:00:00 DateTime dt1 = new DateTime(); //Assign year, month, day DateTime dt2 = new DateTime(2015, 12, 31); //Assign year, month, day, hour, min, seconds DateTime dt3 = new DateTime(2015, 12, 31, 5, 10, 20); //Assign year, month, day, hour, min, seconds, UTC timezone DateTime dt4 = new DateTime(2015, 12, 31, 5, 10, 2, DateTimeKind.Utc);
In the above example, we specify the year, month, and day in the constructor. The year can be 0001To9999, the month can be1To12, the date can be1To31. Setting any other value outside these ranges will cause a runtime exception.
DateTime dt = new DateTime(2015, 12, 32); //Raises an exception: Day out of range
Use different DateTime constructors to set date, time, time zone, calendar, and regionality.
Ticks is a date and time starting from the Gregorian calendar 00:00:00.000 year1Month1Since the day100 nanoseconds interval count. Below, initialize a DateTime object with the scale number.
DateTime dt = new DateTime(636370000000000000); DateTime.MinValue.Ticks; //Minimum value DateTime.MaxValue.Ticks; // Maximum value
The DateTime structure includes static fields, properties, and methods. The following examples demonstrate important static fields and properties.
DateTime currentDateTime = DateTime.Now; //Return the current date and time DateTime todaysDate = DateTime.Today; // Return today's date DateTime currentDateTimeUTC = DateTime.UtcNow;// Return the current UTC date and time DateTime maxDateTimeValue = DateTime.MaxValue; // Return the maximum value of DateTime DateTime minDateTimeValue = DateTime.MinValue; // Returns the minimum value of DateTime
TimeSpan is a structure used to represent time in days, hours, minutes, seconds, and milliseconds.
DateTime dt = new DateTime(2015, 12, 31); TimeSpan ts = new TimeSpan(25,20,55); DateTime newDate = dt.Add(ts); Console.WriteLine(newDate);//1/1/2016 1:20:55 AM
Subtracting two dates results in a TimeSpan.
DateTime dt1 = new DateTime(2015, 12, 31); DateTime dt2 = new DateTime(2016, 2, 2); TimeSpan result = dt2.Subtract(dt1);//33.00:00:00
DateTime structure overloads+,-The == != > < <= >= operators simplify the addition, subtraction, and comparison of dates. These make it easy to handle dates.
DateTime dt1 = new DateTime(2015, 12, 20); DateTime dt2 = new DateTime(2016, 12, 31, 5, 10, 20); TimeSpan time = new TimeSpan(10, 5, 25, 50); Console.WriteLine(dt2 + time); // 1/10/2017Morning10:36:10 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); //True Console.WriteLine(dt1 >= dt2); //False Console.WriteLine(dt1 <= dt2);//True
The DateTime structure contains the following methods to convert dates and times to strings.
Method | Description |
---|---|
ToString | Convert DateTime value to a string in a specified format in the current region. |
ToShortDateString | Convert DateTime value to short date string in the current region (M/d/yyyy format). |
ToShortTimeString | Convert DateTime value to short time string in the current region (h: mm: ss format). |
ToLongDateString | Convert DateTime value to long date string in the current region (dddd, MMMM d, yyyy format). |
ToLongTimeString | Convert DateTime value to long time string in the current region (h:mm:ss tt format). |
The following example demonstrates how to convert DateTime to different string formats.
var dt = DateTime.Now; Console.WriteLine("Date String Current Culture: "); + dt.ToString("d")); Console.WriteLine("MM/dd/yyyy Format:"); + dt.ToString("MM/dd/yyyy")); Console.WriteLine("dddd, dd MMMM yyyy Format:"); + dt.ToString("dddd, dd MMMM yyyy")); Console.WriteLine("MM/dd/yyyy h:mm tt Format:"); + dt.ToString("MM/dd/yyyy h:mm tt")); Console.WriteLine("MMMM dd Format:"); + dt.ToString("MMMM dd")); Console.WriteLine("HH:mm:ss Format:"); + dt.ToString("HH:mm:ss")); Console.WriteLine("hh:mm tt Format:"); + dt.ToString("hh:mm tt")); Console.WriteLine("Short Date String: "); + dt.ToShortDateString()); Console.WriteLine("Long Date String: "); + dt.ToLongDateString()); Console.WriteLine("Short Time String: "); + dt.ToShortTimeString()); Console.WriteLine("Long Time String: "); + dt.ToLongTimeString());
The Parse (), ParseExact (), TryParse (), and TryParseExact () methods can be used to convert valid date and time string to DateTime object.
If the specified string is not a valid representation of a date and time, the Parse () and ParseExact () methods will throw an exception. Therefore, it is recommended to use TryParse () or TryParseExact () methods, as they will return false if the string is invalid.
var str = "5/12/2020"; DateTime dt; var isValidDate = DateTime.TryParse(str, out dt); if(isValidDate) Console.WriteLine(dt); else Console.WriteLine($"{str} is not a valid date string");