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