Home > Back-end >  How do I format a single digit month in C# date formatting?
How do I format a single digit month in C# date formatting?

Time:05-17

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.

CodePudding user response:

“%M" should work. See custom format strings

CodePudding user response:

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