How do I format a single digit month in C# date formatting?

Viewed 230

In C#, if I run this code, it prints out 05:

Console.WriteLine(DateTime.Now.ToString("MM"));

However, if I run this code, it prints out May 16:

Console.WriteLine(DateTime.Now.ToString("M"));

I'm looking for a date format that will print out 5. How do I format a single digit month? To be clear, it would be 1 digit for months 1 to 9, and 2 digits for months 10 to 12.

2 Answers

“%M" should work. See custom format strings


Some explanation:

To resolve this ambiguity you can add a space, which makes it a custom format string, but also adds a space to the resulting value. Or you can add a %.

Right now (May) a DateTime.Now.ToString("%M") results in "5".

Microsoft has some excellent documentation regarding how to format DateTime as string values over at https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings

The parameter you're looking for is M which would make the method call DateTime.Now.ToString("M");.

Update: However, as pointed ut by Hans Kesting, this could give unexpected results in some situations which can be avoided by using a % in combination with the M as described at https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings#UsingSingleSpecifiers

Related