Aaron Franke
Aaron Franke

Reputation: 4022

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

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.

Upvotes: 3

Views: 2771

Answers (2)

Hans Kesting
Hans Kesting

Reputation: 39255

“%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".

Upvotes: 7

Maritim
Maritim

Reputation: 2159

Microsoft has some excellent documentation regarding how to format DateTime as string values over at https://learn.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://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings#UsingSingleSpecifiers

Upvotes: -2

Related Questions