Search code examples
c#datetimedate-formatting

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.


Solution

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