Search⌘ K
AI Features

Date and Time Operations

Explore how to use C#'s DateTime struct to format dates and times flexibly, parse string inputs safely, and calculate durations with TimeSpan. Understand culture-specific formatting and modern string interpolation to display dates appropriately in your applications.

By default, when we print a DateTime object, it has a rigid and sometimes inconvenient format.

C# 14.0
var dateTime = new DateTime(2021, 12, 24, 17, 45, 23);
Console.WriteLine(dateTime); // Output: 12/24/2021 17:45:23
  • Line 1: We initialize a specific DateTime instance.

  • Line 2: We print the object directly to the console, which yields the default output format.

The default format often lacks the readability required for user-facing applications, but C# provides several ways to customize this output.

Note: The exact text output of DateTime heavily depends on the host system’s local culture settings. For example, a system in the US will print 12/24/2021, while a system in Europe will print 24/12/2021. The outputs shown in this lesson use the default US English culture.

Output format methods

The DateTime struct offers several output-formatting methods. Each provides a different representation of the data:

  • ToLocalTime(): This assumes the time inside the DateTime object is in UTC and converts it to local time.

  • ToUniversalTime(): This assumes the time inside the DateTime object is in the local time zone and converts it to UTC.

  • ToLongDateString(): This returns a string version of the date with the month written in words.

  • ToShortDateString() ...