views:

246

answers:

6

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?

+7  A: 

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.

Franci Penov
The %M is what I was looking for. Thanks!
Mike Gates
+5  A: 

Why not use DateTime.Now.Month?

Roatin Marth
+4  A: 

You can also use System.DateTime.Now.Month.ToString(); to accomplish the same thing

Michael Kniskern
+1  A: 

You can put an empty string literal in the format to make it a composite format:

DateTime.Now.ToString("''M")
Guffa
+8  A: 

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");
JaredPar
+1 Thanks for explaining the issue, as well as providing a workaround.
Odrade
A: 

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.

robyaw