'Strange behaviour of the "M" custom format specifier in c#

This Code produces the output in the comments bellow each Console.WriteLine statement.

Can anyone explain this kind of behaviour?

DateTime date1 = new DateTime(2008, 8, 18);
Console.WriteLine(date1.ToString("M"));
// Displays August 18

Console.WriteLine(date1.ToString("M "));
// Displays 8

Console.WriteLine(date1.ToString("(M)"));
// Displays (8)

Console.WriteLine(date1.ToString("(M) MMM, MMMM"));
// Displays (8) Aug, August


Solution 1:[1]

Can anyone explain this kind of behaviour?

Yes, it's completely documented in standard date and time format strings and custom date and time format strings.

Let's go through them one at a time:

  • date1.ToString("M"): That uses a single character 'M', so it's the standard format string for "month/day pattern"
  • date1.ToString("M "): That uses a format string with two characters, so it's a custom format string using M which is the month number, 1-12 with no padding.
  • date1.ToString("(M)"): Again, a custom format string using M
  • date1.ToString("(M) MMM, MMMM"): A custom format string using M, as well as MMM ("abbreviated name of the month") and MMMM (" full name of the month")

The important difference between the first two is that a format string is only considered to be a standard format if it's a single character. Otherwise, it's considered to be a custom format. If you want to use a single-character custom format specifier on its own, you can use % as a leading character - so date1.ToString("%M") would return "8" rather than "August 18".

Solution 2:[2]

Date and Time in C# are handled by DateTime struct in C# that provides properties and methods to format dates in different datetime formats.

M-> Month number(eg.3)

MM-> Month number with leading zero(eg.04)

MMM-> Abbreviated Month Name (e.g. Dec)

MMMM-> Full month name (e.g. December)

https://www.c-sharpcorner.com/blogs/date-and-time-format-in-c-sharp-programming1

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jon Skeet
Solution 2