Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 393
Aaron Franke Avatar asked Oct 15 '25 14:10

Aaron Franke


1 Answers

“%M" should work. See custom format strings


Some explanation:

  • The "M" can be part of a custom format string, where it means a "month number" in one or two digits
  • But on itself it can also be a standard format string meaning a "month day pattern" - as the OP found out.

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

like image 86
Hans Kesting Avatar answered Oct 17 '25 04:10

Hans Kesting



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!