DateTime Structure

The System.DateTime structure represents an instant in time, expressed as a date and time of day. It is a value type that provides a wealth of functionality for date and time manipulation.

Overview

The DateTime structure is fundamental for handling temporal data in .NET. It can store dates ranging from January 1, 0001, to December 31, 9999, and times from midnight to 23:59:59.9999999.

Key properties of a DateTime object include:

  • Year: The year.
  • Month: The month.
  • Day: The day.
  • Hour: The hour.
  • Minute: The minute.
  • Second: The second.
  • Millisecond: The millisecond.
  • DayOfWeek: The day of the week.
  • DayOfYear: The day of the year.

Creating DateTime Objects

DateTime objects can be created in several ways:

Using Constructors

The most common way to create a DateTime object is by using its constructors. These allow you to specify the year, month, day, hour, minute, and second.


// Creating a specific date and time
DateTime specificDateTime = new DateTime(2023, 10, 27, 10, 30, 0);

// Creating just a date
DateTime justADate = new DateTime(2024, 1, 1);

// Creating a date and time with milliseconds
DateTime dateTimeWithMs = new DateTime(2023, 10, 27, 10, 30, 0, 500);
                

Using Static Properties and Methods

DateTime provides several useful static properties and methods for common scenarios:

  • DateTime.Now: Gets the current date and time on this computer, expressed as the local time.
  • DateTime.UtcNow: Gets the current date and time on this computer, expressed as Coordinated Universal Time (UTC).
  • DateTime.Today: Gets the current date.
  • DateTime.Parse(): Converts the string representation of a date and time to its DateTime equivalent.
  • DateTime.ParseExact(): Converts the string representation of a date and time to its DateTime equivalent using a specified format.

// Get current date and time
DateTime now = DateTime.Now;
Console.WriteLine($"Current local time: {now}");

// Get current UTC time
DateTime utcNow = DateTime.UtcNow;
Console.WriteLine($"Current UTC time: {utcNow}");

// Get today's date
DateTime today = DateTime.Today;
Console.WriteLine($"Today's date: {today}");

// Parsing a date string
string dateString = "27/10/2023";
DateTime parsedDate = DateTime.ParseExact(dateString, "dd/MM/yyyy", null);
Console.WriteLine($"Parsed date: {parsedDate.ToShortDateString()}");
                

Date and Time Manipulation

DateTime objects are immutable. Operations that appear to modify a DateTime object actually return a new DateTime object with the changes applied. Common manipulation methods include:

Adding Time

  • AddDays()
  • AddMonths()
  • AddYears()
  • AddHours()
  • AddMinutes()
  • AddSeconds()
  • AddMilliseconds()

DateTime initialDate = new DateTime(2023, 10, 27);
DateTime futureDate = initialDate.AddDays(10).AddMonths(2);
Console.WriteLine($"Initial: {initialDate.ToShortDateString()}, Future: {futureDate.ToShortDateString()}");
                

Subtracting Time

Use the Subtract() method or the subtraction operator (-). This often returns a TimeSpan object, which represents a duration.


DateTime startDate = new DateTime(2023, 10, 27, 12, 0, 0);
DateTime endDate = new DateTime(2023, 10, 29, 14, 30, 0);

TimeSpan duration = endDate.Subtract(startDate);
Console.WriteLine($"Duration: {duration.TotalHours} hours");

DateTime pastDate = initialDate.AddDays(-5);
Console.WriteLine($"5 days ago: {pastDate.ToShortDateString()}");
                

Formatting DateTime Objects

The ToString() method is invaluable for formatting DateTime objects into human-readable strings. You can use predefined format strings or custom format strings.

Predefined Format Strings

  • "d": Short date pattern (e.g., 10/27/2023)
  • "D": Long date pattern (e.g., Friday, October 27, 2023)
  • "t": Short time pattern (e.g., 10:30 AM)
  • "T": Long time pattern (e.g., 10:30:00 AM)
  • "f": Full date/short time pattern (e.g., Friday, October 27, 2023 10:30 AM)
  • "F": Full date/long time pattern (e.g., Friday, October 27, 2023 10:30:00 AM)
  • "g": General date/short time pattern (e.g., 10/27/2023 10:30 AM)
  • "G": General date/long time pattern (e.g., 10/27/2023 10:30:00 AM)
  • "o": Round-trip format (e.g., 2023-10-27T10:30:00.0000000)
  • "s": Sortable format (e.g., 2023-10-27T10:30:00)
  • "u": Universal sortable format (e.g., 2023-10-27 10:30:00Z)
  • "yyyy-MM-dd HH:mm:ss": Custom format example

DateTime myDateTime = new DateTime(2023, 10, 27, 10, 30, 0);

Console.WriteLine($"Short Date: {myDateTime.ToString("d")}");
Console.WriteLine($"Long Date: {myDateTime.ToString("D")}");
Console.WriteLine($"Short Time: {myDateTime.ToString("t")}");
Console.WriteLine($"General (short time): {myDateTime.ToString("g")}");
Console.WriteLine($"Custom format: {myDateTime.ToString("yyyy-MM-dd HH:mm:ss")}");
                

Comparisons

DateTime objects can be compared using standard comparison operators (<, >, <=, >=, ==, !=) or using the CompareTo() method.


DateTime date1 = new DateTime(2023, 10, 27);
DateTime date2 = new DateTime(2023, 11, 1);

if (date1 < date2) {
    Console.WriteLine("date1 is before date2");
}

if (date1.CompareTo(date2) < 0) {
    Console.WriteLine("date1 is earlier than date2 (using CompareTo)");
}
                

Time Spans

A TimeSpan represents a duration or the difference between two DateTime objects. It can store days, hours, minutes, seconds, and milliseconds.


DateTime start = new DateTime(2023, 10, 27, 9, 0, 0);
DateTime end = new DateTime(2023, 10, 27, 17, 30, 0);
TimeSpan workHours = end - start;

Console.WriteLine($"Total hours worked: {workHours.TotalHours}"); // 8.5
Console.WriteLine($"Minutes worked: {workHours.TotalMinutes}");   // 510