Mike Gates
Mike Gates

Reputation: 1904

DotNet DateTime.ToString strange results

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

Answers (6)

robyaw
robyaw

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

Michael Kniskern
Michael Kniskern

Reputation: 25260

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

Upvotes: 4

JaredPar
JaredPar

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

Guffa
Guffa

Reputation: 700272

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

DateTime.Now.ToString("''M")

Upvotes: 2

Roatin Marth
Roatin Marth

Reputation: 24085

Why not use DateTime.Now.Month?

Upvotes: 5

Franci Penov
Franci Penov

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

Related Questions