Date and Times

.Date and Times
DateTime Structure | DateTime Formatting | TimeSpan Structure | Calendar Class | DateTime Validation

"A DateTime represents an instant in time while a TimeSpan represents a time interval. TimeSpans can be added to DateTimes to obtain new DateTimes. The difference between two DateTimes is a TimeSpan."

Date and Times are represented in C# by the DateTime public structure. The DateTime structure contains methods and properties to help with date and time computations. Time intervals are represented by the TimeSpan public structure. Differences between DateTimes are measured in TimeSpans. Also, TimeSpans can be added to DateTimes to obtain new DateTimes. The Calendar class represents time in units of weeks, months, and years.




DateTime Structure

.DateTime Properties and Methods
DateTime Methods and Properties

DateTime is a structure which represents dates and times with values ranging from 12:00:00 midnight, January 1, 0001 Anno Domini through 11:59:59 P.M., December 31, 9999 A.D. These limits are stored as read-only values in the MinValue and MaxValue fields. Time values are measured in 100-nanosecond units called ticks, and a particular date is expressed as the number of ticks that have elapsed since the MinValue. For example, a tick value of 31241376000000000L represents Friday, January 01, 0100 12:00:00 midnight.

There are several methods and properties for working with DateTime values. Note that just like strings, DateTIme values are immutable. The example program below illustrates some to the DateTime Methods and Properties.

DateTime Methods and Properties

using System;

class Program
{
    static void Main()
    {
        // Static properties
        Console.WriteLine(" ---  Static DateTime Properties  ---");
        Console.WriteLine("Now   : {0}", DateTime.Now);   // Local Time Zone
        Console.WriteLine("Today : {0}", DateTime.Today);
        Console.WriteLine("UtcNow: {0}", DateTime.UtcNow); // Greenwich Mean Time
        // GMT - 5 hours = Central Daylight Time
        // GMT - 6 hours = Central Standard Time

        // Instance properties
        Console.WriteLine("\n --- Instance DateTime Properties ---");
        DateTime myDateTime = new DateTime();
        Console.WriteLine("Unitialized Date: {0}", myDateTime.Date); // 1/1/0001 12:00:00 AM
        Console.WriteLine("Halley's Comet  : {0}", new DateTime(2061, 7, 28)); // 7/28/2061

        // Set End of World in Local Time
        DateTime endOfWorld = new DateTime(2112, 4, 10, 13, 55, 53, DateTimeKind.Local);
        Console.WriteLine("End of World : {0}", endOfWorld); // 4/10/2112 1:55:53 PM
        Console.WriteLine("Kind       : {0}", endOfWorld.Kind); // Local
        DateTime endOfWorldUtc = endOfWorld.ToUniversalTime();
        Console.WriteLine("Kind       : {0}", endOfWorldUtc.Kind); // Utc
        Console.WriteLine("Year       : {0}", endOfWorld.Year); // 2112
        Console.WriteLine("Month      : {0}", endOfWorld.Month); // 4
        Console.WriteLine("Day        : {0}", endOfWorld.Day); // 10
        Console.WriteLine("DayOfWeek  : {0}", endOfWorld.DayOfWeek); // Sunday
        Console.WriteLine("DayOfYear  : {0}", endOfWorld.DayOfYear); // 101 (Gregorian)
        Console.WriteLine("Hour       : {0}", endOfWorld.Hour); // 13
        Console.WriteLine("Minute     : {0}", endOfWorld.Minute); // 55
        Console.WriteLine("Second     : {0}", endOfWorld.Second); // 53
        Console.WriteLine("Millisecond: {0}", endOfWorld.Millisecond); // 0
        Console.WriteLine("Date       : {0}",endOfWorld.Date); // 4/10/2112 12:00:00 AM
        Console.WriteLine("TimeOfDay  : {0}", endOfWorld.TimeOfDay); // 13:55:53

        // Add Hours and Check for Equality
        if (endOfWorld.AddHours(5).Equals(endOfWorldUtc))
            Console.WriteLine("Dates are equal"); // Equal
        else
            Console.WriteLine("Dates are not equal");
       
        // Compare Dates
        int compareResult = endOfWorld.CompareTo(endOfWorldUtc);
        switch (compareResult)
        {
            case 0 :
                Console.WriteLine("Switch dates are equal");
                break;
            default :
                if (compareResult > 0)
                    Console.WriteLine("endofWorld is before endOfWorldUtc");
            else
                    Console.WriteLine("endofWorld is later than endOfWorldUtc");  // Later
                break;
        }
        Console.WriteLine();
    }
}

Top




DateTime Formatting

.DateTime Standard and Custom Formats
Standard and Custom Date and Time Formatting

A date and time format string defines the text representation of a DateTime value. It can also define the representation of a date and time value that is required in a parsing operation in order to successfully convert the string to a date and time. DateTimes can be formatted with either with the ToString method of a date and time instance or with a method that supports composite formatting, such as Console.WriteLine(). DateTimes can be formatted using either Standard Format Strings or Custom Format Strings.

Standard Date and Time Format String

A Standard Date and Time Format String uses a single format specifier to define the text representation of a date and time value. Any date and time format string that contains more than one character, including white space, is interpreted as a custom date and time format string. (See examples of standard formatting below which use the date time DateTime theDate = new DateTime(2014, 6, 19, 16, 43, 37, 500, DateTimeKind.Local);)

Standard Date and Time Format Specifiers
Format specifier Description Examples
"d" Short date pattern. 6/19/2014
"D" Long date pattern. Thursday, June 19, 2014
"f" Full date/time pattern (short time). Thursday, June 19, 2014 4:43 PM
"F" Full date/time pattern (long time). Thursday, June 19, 2014 4:43:37 PM
"g" General date/time pattern (short time). 6/19/2014 4:43 PM
"G" General date/time pattern (long time). 6/19/2014 4:43:37 PM
"M", "m" Month/day pattern. June 19
"O", "o" Round-trip date/time pattern. 2014-06-19T16:43:37.5000000-05:00
"R", "r" RFC1123 pattern. Thu, 19 Jun 2014 16:43:37 GMT
"s" Sortable date/time pattern. 2014-06-19T16:43:37
"t" Short time pattern. 4:43 PM
"T" Long time pattern. 4:43:37 PM
"u" Universal sortable date/time pattern. 2014-06-19 16:43:37Z
"U" Universal full date/time pattern. Thursday, June 19, 2014 9:43:37 PM
"Y","y" Year month pattern. June, 2014


Custom Date and Time Format String

A Custom Date and Time Format String consists of one or more custom date and time format specifiers to define the text representation of a date and time value. Any string that is not a standard date and time format string is interpreted as a custom date and time format string.

Custom Time and Date Format Specifiers
Format specifier Description Examples
"d" The day of the month, from 1 through 31. 6/1/2009 1:45:30 PM -> 1
6/15/2009 1:45:30 PM -> 15

"dd"

The day of the month, from 01 through 31. 6/1/2009 1:45:30 PM -> 01
6/15/2009 1:45:30 PM -> 15

"ddd"

The abbreviated name of the day of the week. 6/15/2009 1:45:30 PM -> Mon (en-US)
6/15/2009 1:45:30 PM -> Пн (ru-RU)
6/15/2009 1:45:30 PM -> lun. (fr-FR)
"dddd" The full name of the day of the week. 6/15/2009 1:45:30 PM -> Monday (en-US)
6/15/2009 1:45:30 PM -> понедельник (ru-RU)
6/15/2009 1:45:30 PM -> lundi (fr-FR)
"f", "ff", "fff", etc. The tenths, hundredths, thousands of a second in a date and time value. 6/15/2009 13:45:30.617 -> 6
6/15/2009 13:45:30.050 -> 0
"g", "gg" The period or era. 6/15/2009 1:45:30 PM -> A.D.
"h" The hour, using a 12-hour clock from 1 to 12. 6/15/2009 1:45:30 AM -> 1
6/15/2009 1:45:30 PM -> 1
"hh" The hour, using a 12-hour clock from 01 to 12. 6/15/2009 1:45:30 AM -> 01
6/15/2009 1:45:30 PM -> 01
"H" The hour, using a 24-hour clock from 0 to 23. 6/15/2009 1:45:30 AM -> 1
6/15/2009 1:45:30 PM -> 13
"HH" The hour, using a 24-hour clock from 00 to 23. 6/15/2009 1:45:30 AM -> 01
6/15/2009 1:45:30 PM -> 13
"K" Time zone information. 6/15/2009 1:45:30 PM, Kind Unspecified ->
6/15/2009 1:45:30 PM, Kind Utc -> Z
6/15/2009 1:45:30 PM, Kind Local -> -07:00 (depends on local computer settings)
"m" The minute, from 0 through 59. 6/15/2009 1:09:30 AM -> 9
6/15/2009 1:09:30 PM -> 9
"mm" The minute, from 00 through 59. 6/15/2009 1:09:30 AM -> 09
6/15/2009 1:09:30 PM -> 09
"M" The month, from 1 through 12. 6/15/2009 1:45:30 PM -> 6
"MM" The month, from 01 through 12. 6/15/2009 1:45:30 PM -> 06
"MMM" The abbreviated name of the month. 6/15/2009 1:45:30 PM -> Jun (en-US)
6/15/2009 1:45:30 PM -> juin (fr-FR)
6/15/2009 1:45:30 PM -> Jun (zu-ZA)
"MMMM" The full name of the month. 6/15/2009 1:45:30 PM -> June (en-US)
6/15/2009 1:45:30 PM -> juni (da-DK)
6/15/2009 1:45:30 PM -> uJuni (zu-ZA)
"s" The second, from 0 through 59. 6/15/2009 1:45:09 PM -> 9
"ss" The second, from 00 through 59. 6/15/2009 1:45:09 PM -> 09
"t" The first character of the AM/PM designator. 6/15/2009 1:45:30 PM -> P (en-US)
6/15/2009 1:45:30 PM -> 午 (ja-JP)
6/15/2009 1:45:30 PM -> (fr-FR)
"tt" The AM/PM designator. 6/15/2009 1:45:30 PM -> PM (en-US)
6/15/2009 1:45:30 PM -> 午後 (ja-JP)
6/15/2009 1:45:30 PM -> (fr-FR)
"y" The year, from 0 to 99. 1/1/0001 12:00:00 AM -> 1
1/1/0900 12:00:00 AM -> 0
1/1/1900 12:00:00 AM -> 0
6/15/2009 1:45:30 PM -> 9
"yy" The year, from 00 to 99. 1/1/0001 12:00:00 AM -> 01
1/1/0900 12:00:00 AM -> 00
1/1/1900 12:00:00 AM -> 00
6/15/2009 1:45:30 PM -> 09
"yyy" The year, with a minimum of three digits. 1/1/0001 12:00:00 AM -> 001
1/1/0900 12:00:00 AM -> 900
1/1/1900 12:00:00 AM -> 1900
6/15/2009 1:45:30 PM -> 2009
"yyyy" The year as a four-digit number. 1/1/0001 12:00:00 AM -> 0001
1/1/0900 12:00:00 AM -> 0900
1/1/1900 12:00:00 AM -> 1900
6/15/2009 1:45:30 PM -> 2009
"yyyyy" The year as a five-digit number. 1/1/0001 12:00:00 AM -> 00001
6/15/2009 1:45:30 PM -> 02009


DateTime Formatting

using System;

namespace DateTimeFormat
{
    class Program
    {
        static void Main()
        {
            DateTime theDate = new DateTime(2014, 6, 19, 16, 43, 37, 500, DateTimeKind.Local);

            Console.WriteLine("---  Custom Date Formats  ---");
            // Custom Date Format with ToString() method           
            Console.WriteLine("(\"MMMM dd, yyyy\")    -> " +
                              theDate.ToString("MMMM dd, yyyy") + "\n");

            // Custom Format with Composite Formatting of WriteLine() method
            Console.WriteLine("{{0:MM/dd/yy H:mm:ss}} -> {0:MM/dd/yy H:mm:ss}\n", theDate);
           

            Console.WriteLine("\n--- Standard Date Formats ---");
            Console.WriteLine("d -> {0:d}", theDate);
            Console.WriteLine("D -> {0:D}\n", theDate);

            Console.WriteLine("f -> {0:f}", theDate);
            Console.WriteLine("F -> {0:F}\n", theDate);

            Console.WriteLine("g -> {0:g}", theDate);
            Console.WriteLine("G -> {0:G}\n", theDate);

            Console.WriteLine("M, m -> {0:M}\n", theDate);

            Console.WriteLine("O, o -> {0:O}\n", theDate);
           
            Console.WriteLine("R, r -> {0:R}\n", theDate);

            Console.WriteLine("s -> {0:s}\n", theDate);

            Console.WriteLine("t -> {0:t}", theDate);
            Console.WriteLine("T -> {0:T}\n", theDate);

            Console.WriteLine("u -> {0:u}", theDate);
            Console.WriteLine("U -> {0:U}\n", theDate);

            Console.WriteLine("Y, y -> {0:Y}\n", theDate);

            Console.WriteLine();
        }
    }
}
using System;

namespace DateTimeFormat
{
    class Program
    {
        static void Main()
        {
            DateTime theDate = new DateTime(2014, 6, 19, 16, 43, 37, 500, DateTimeKind.Local);

            Console.WriteLine("---  Custom Date Formats  ---");
            // Custom Date Format with ToString() method           
            Console.WriteLine("(\"MMMM dd, yyyy\")    -> " +
                              theDate.ToString("MMMM dd, yyyy") + "\n");

            // Custom Format with Composite Formatting of WriteLine() method
            Console.WriteLine("{{0:MM/dd/yy H:mm:ss}} -> {0:MM/dd/yy H:mm:ss}\n", theDate);
           

            Console.WriteLine("\n--- Standard Date Formats ---");
            Console.WriteLine("d -> {0:d}", theDate);
            Console.WriteLine("D -> {0:D}\n", theDate);

            Console.WriteLine("f -> {0:f}", theDate);
            Console.WriteLine("F -> {0:F}\n", theDate);

            Console.WriteLine("g -> {0:g}", theDate);
            Console.WriteLine("G -> {0:G}\n", theDate);

            Console.WriteLine("M, m -> {0:M}\n", theDate);

            Console.WriteLine("O, o -> {0:O}\n", theDate);
           
            Console.WriteLine("R, r -> {0:R}\n", theDate);

            Console.WriteLine("s -> {0:s}\n", theDate);

            Console.WriteLine("t -> {0:t}", theDate);
            Console.WriteLine("T -> {0:T}\n", theDate);

            Console.WriteLine("u -> {0:u}", theDate);
            Console.WriteLine("U -> {0:U}\n", theDate);

            Console.WriteLine("Y, y -> {0:Y}\n", theDate);

            Console.WriteLine();
        }
    }
}

Top




TimeSpan Structure

.TimeSpan Structure

C# uses the TimeSpan structure to represent a time interval. TimeSpans are measured as a positive or negative number of days, hours, minutes, seconds, and fractions of a second. The TimeSpan structure can also be used to represent the time of day, but only if the time is unrelated to a particular date. The largest unit of time that the TimeSpan structure uses to measure duration is a day; The value of a TimeSpan object can range from TimeSpan.MinValue (about negative 10 million days) to TimeSpan.MaxValue (about 10 million days). The value of a TimeSpan object is the number of ticks that equal the represented time interval. A tick is equal to 100 nanoseconds.

TimeSpans can be created by the implicit or explicit constructors. TimeSpans can also be created as a return value from operations, such as arithmetic operations on DateTimes. Additionally, strings can be converted to TimeSpans by using the Parse, TryParse, ParseExact, or TryParseExact methods.

A special class called Stopwatch was developed for benchmarking elapsed times inside programs and is often used for code optimization. Stopwatch must be created as an instance which makes it useful for multi-threaded applications and websites. The Stopwatch class is defined in the System.Diagnostics namespace.

TimeSpan Structure

using System;

namespace TimeSpanExample
{
    class Program
    {
        static void Main()
        {
            // TimeSpan Static Properties
            Console.WriteLine(" ---      Static TimeSpan Properties    ---");
            Console.WriteLine(" ------------------------------------------");
            Console.WriteLine("Min TimeSpan is {0}", TimeSpan.MinValue);
            // Prints: -10675199.02:48:05.4775808 (negative 10 million days+)
            Console.WriteLine("Max TimeSpan is {0}", TimeSpan.MaxValue);
            // Prints: 10675199.02:48:05.4775807 (10 million days+)

            // 1. Implicit Default Constructor
            Console.WriteLine("\n ---        Implicit Constructor        ---");
            Console.WriteLine(" ------------------------------------------");
            TimeSpan interval1 = new TimeSpan();
            Console.WriteLine(interval1.Equals(TimeSpan.Zero)); // Prints: True
            Console.WriteLine(interval1); // Prints: 00:00:00

            // 2. Explicit Default Constructor (Days, Hours, Minutes, Seconds, Milliseconds)
            Console.WriteLine("\n ---        Explicit Constructor        ---");
            Console.WriteLine(" ------------------------------------------");
            TimeSpan interval2 = new TimeSpan(2, 4, 40, 36, 500);
            Console.WriteLine(interval2.ToString());  // Prints: 2.04:40:36.5000000

            // 3. TimeSpan Returned from Operation
            Console.WriteLine("\n --- TimeSpans Returned from Operations ---");
            Console.WriteLine(" ------------------------------------------");
            DateTime departure = new DateTime(2014, 6, 15, 10, 26, 0);
            DateTime arrival = new DateTime(2014, 6, 16, 21, 18, 0);
            TimeSpan travelTime = arrival - departure;
            TimeSpan travelTime2 = arrival.Subtract(departure);
            Console.WriteLine("{0} - {1} = {2}", arrival, departure, travelTime);
            Console.WriteLine("{0} - {1} = {2}", arrival, departure, travelTime2);
            // Prints: 6/16/2014 9:18:00 PM - 6/15/2014 10:26:00 AM = 1.10:52:00

            // 4. Convert Strings to TimeSpans
            Console.WriteLine("\n ---  Converting Strings to TimeSpans   ---");
            Console.WriteLine(" ------------------------------------------");
            string[] values = { "12", "3.6:21:35", "10:23:59.995", "1.8", "1.8:62" };
            foreach (string value in values)
            {
                try
                {
                    TimeSpan ts = TimeSpan.Parse(value);
                    Console.WriteLine("{0,12} -> {1}", value, ts);
                }
                catch (FormatException)
                {
                    Console.WriteLine("{0,12} -> Error: unable to parse ", value);
                }
                catch (OverflowException)
                {
                    Console.WriteLine("{0,12} -> Error: outside TimeSpan range", value);
                }
            }
            // Prints:
            // 12           -> 12.00:00:00
            // 3.6:21:35    -> 3.06:21:35
            // 10:23:59.995 -> 10:23:59.9950000
            // 1.8    -> Error: unable to parse
            // 1.8:62 -> Error: outside TimeSpan range
            Console.WriteLine();
        }
    }
}

Top




Calendar Class

.Calendar Class
Calendar Class

Each CultureInfo contains a default calendar in theCalendar property. Also the OptionalCalendars property contains a list of alternative calendars for the culture. An application can change the calendar by setting the Calendar property of the DateTimeFormat, however the calendar chosen must be one of the calendars listed in OptionalCalendars. Calendar names are listed in the System.Globalization namespace.

The DateTime class uses the default calendar to format date and times. The Gregorian calendar, also called the "Western calendar", has become a de facto international standard. Most cultures will use the Gregorian calendar. However the date and time formatting information can always be retrieved with the DateTimeFormatInfo class. The properties of the DateTimeFormatInfo class contain culture-specific information for formatting or parsing date and time values such as the following:

  1. The patterns used to format date values.
  2. The patterns used to format time values.
  3. The names of the days of the week.
  4. The names of the months of the year.
  5. The A.M. and P.M. designators used in time values.
  6. The calendar in which dates are expressed.
Calendar Class

using System;
using System.Globalization;

namespace CalendarExample
{
    class Program
    {
        static void Main()
        {
            // Current Culture Calendar Settings
            Console.WriteLine("--- Current CultureInfo Calendar Settings ---");
            Console.WriteLine("CurrentCulture -> {0}", CultureInfo.CurrentCulture);
            Console.WriteLine("CurrentCulture.Calendar -> {0}", CultureInfo.CurrentCulture.Calendar);
            Console.WriteLine("CurrentCulture.OptionalCalendars -> {0}", CultureInfo.CurrentCulture.OptionalCalendars);

            // Current Date Time Defaults
            Console.WriteLine("\n---       Current DateTime Defaults       ---");
            Console.WriteLine("{0:g}",DateTime.Now);  // Gegorian Calendar
            Console.WriteLine("{0:g}", DateTime.UtcNow); // Gegorian Calendar

            // Create French Culture and Date
            Console.WriteLine("\n---     Create French Culture and Date    ---");
            DateTime myDT = new DateTime(2002, 1, 3, 13, 30, 45);
            CultureInfo myCIfrFR = new CultureInfo("fr-FR", false);
            Console.WriteLine("{0}: {1}", CultureInfo.CurrentCulture, myDT.ToString("f"));
            Console.WriteLine("fr-FR: {0}\n", myDT.ToString("f", myCIfrFR));
        }
    }
}

Top




DateTime Validation

.DateTime TryParse
DateTime TryParse

DateTime values can be parsed for validation with the following methods():

  1. DateTime.Parse
  2. DateTime.TryParse
  3. DateTime.ParseExact
  4. DateTime.TryParseExact

The "Try" methods do not cause an exception if validation fails, while the other methods do cause an exception on validation failure. If the input string does not contain any indication of the time zone, the date and time parsing methods interpret the value of the date and time string based on the time zone setting for the operating system, unless the AssumeUniversal option is used. To convert the date and time to the Universal Time AdjustToUniversal options can be used. The DateTimeStyles Enumeration defines the formatting options that customize string parsing and includes the following members:

  1. AdjustToUniversal - Date and time are returned as a Coordinated Universal Time (UTC).
  2. AllowInnerWhite - Extra white-space characters in the middle of the string must be ignored during parsing, except if they occur in the DateTimeFormatInfo format patterns.
  3. AllowLeadingWhite - Leading white-space characters must be ignored during parsing, except if they occur in the DateTimeFormatInfo format patterns.
  4. AllowTrailingWhite - Trailing white-space characters must be ignored during parsing, except if they occur in the DateTimeFormatInfo format patterns.
  5. AllowWhiteSpaces - Extra white-space characters anywhere in the string must be ignored during parsing, except if they occur in the DateTimeFormatInfo format patterns. This value is a combination of the AllowLeadingWhite, AllowTrailingWhite, and AllowInnerWhite values.
  6. AssumeLocal - If no time zone is specified in the parsed string, the string is assumed to denote a local time.
    This value cannot be used with AssumeUniversal or RoundtripKind.
  7. AssumeUniversal - If no time zone is specified in the parsed string, the string is assumed to denote a UTC.
    This value cannot be used with AssumeLocal or RoundtripKind.
  8. NoCurrentDateDefault - If the parsed string contains only the time and not the date, the parsing methods assume the Gregorian date with year = 1, month = 1, and day = 1.
  9. None - Default formatting options must be used. This value represents the default style for the DateTime.Parse, DateTime.ParseExact, and DateTime.TryParse methods.
  10. RoundtripKind - The DateTimeKind field of a date is preserved when a DateTime object is converted to a string using the "o" or "r" standard format specifier, and the string is then converted back to a DateTime object.
DateTime TryParse

using System;

namespace DateTimeInput
{
    class Program
    {
        static void Main(string[] args)
        {
            string dateString;
            DateTime dateValue;

            while (true)
            {
               dateString = Console.ReadLine();
               if (DateTime.TryParse(dateString, out dateValue))
                  Console.WriteLine("You entered the valid date of: {0}\n", dateValue);
               else
                 Console.WriteLine("Error: invalid date: {0}\n", dateString);
            }
        }
    }
}

Top



Reference Articles

Top