Search⌘ K

Formatting the Output

Explore how to manipulate and format DateTime objects in C# to produce user-friendly output. Understand various formatting methods and the use of ToString parameters to customize date and time displays effectively.

The problem

By default, when we print the DateTime object, it has an inconvenient format:

C#
using System;
namespace DateTimeFormatting
{
class Program
{
static void Main(string[] args)
{
var dateTime = new DateTime(2021, 12, 24, 17, 45, 23); // 12/24/2021 17:45:23
Console.WriteLine(dateTime);
}
}
}

This format may not be user-friendly. Fortunately, there are ways to change the output according to our needs.

Output format methods

...