When formatting a DateTime, a DateOnly or a TimeOnly, you typically pass a format string to help the user interpret the values.

For example, rather than this:

	var currentDateTime = DateTime.Now;
	Console.WriteLine(currentDateTime);

defaultDateTime

We do this:

var currentDateTime = DateTime.Now;
Console.WriteLine($"{currentDateTime:dd MMM yyyy}");

formattedDateTIme

Suppose we wanted to supply the format string at runtime.

You might be tempted to do this:

var formatString = "dd MMM yyyy";
var currentDateTime = DateTime.Now;
Console.WriteLine($"{currentDateTime:formatString}");

This is not correct.

It’s dangerous because it will run but produce gibberish depending on the date and time.

gibberishDateTime

Using this syntax, the format string must be provided at compile time.

The proper way to do this is to independently format the DateTime and provide that to the string interpolation.

We achieve this using the overload for ToString that accepts a format string.

var formatString = "dd MMM yyyy";
var formattedDateTime = DateTime.Now.ToString(formatString);
Console.WriteLine($"{formattedDateTime}");

This returns what we expect.

RuntimeFormattedDateTime

TLDR

To provide a format string at runtime for formatting, use the ToString method of the DateTime.

Happy hacking!