Reputation: 1904
Why does:
DateTime.Now.ToString("M")
not return the month number? Instead it returns the full month name with the day on it.
Apparently, this is because "M" is also a standard code for the MonthDayPattern. I don't want this...I want to get the month number using "M". Is there a way to turn this off?
Upvotes: 4
Views: 914
Reputation: 2311
It's worth mentioning that the % prefix is required for any single-character format string when using the DateTime.ToString(string)
method, even if that string does not represent one of the built-in format string patterns; I came across this issue when attempting to retrieve the current hour. For example, the code snippet:
DateTime.Now.ToString("h")
will throw a FormatException
. Changing the above to:
DateTime.Now.ToString("%h")
gives the current date's hour.
I can only assume the method is looking at the format string's length and deciding whether it represents a built-in or custom format string.
Upvotes: 0
Reputation: 25260
You can also use System.DateTime.Now.Month.ToString();
to accomplish the same thing
Upvotes: 4
Reputation: 754625
What's happening here is a conflict between standard DateTime
format strings and custom format specifiers. The value "M" is ambiguous in that it is both a standard and custom format specifier. The DateTime
implementation will choose a standard formatter over a customer formatter in the case of a conflict, hence it is winning here.
The easiest way to remove the ambiguity is to prefix the M with the % char. This char is way of saying the following should be interpreted as a custom formatter
DateTime.Now.ToString("%M");
Upvotes: 8
Reputation: 700272
You can put an empty string literal in the format to make it a composite format:
DateTime.Now.ToString("''M")
Upvotes: 2
Reputation: 75991
According to MSDN, you can use either "%M"
, "M "
or " M"
(note: the last two will also include the space in the result) to force M being parsed as the number of month format.
Upvotes: 9