Dotnet DateTime.ToString strange results

Why:

DateTime.Now.ToString("M") 

not return the month number? Instead, it returns the full name of the month with a day on it.

This is apparently because "M" is also the standard code for MonthDayPattern. I do not want this ... I want to get the month number using "M". Is there any way to disable this?

+4
source share
6 answers

According to MSDN, you can use either "%M" , "M " , or " M" ( note : the last two will contain a space as a result) to force M to be parsed as the number of the month format.

+9
source

There is a conflict between standard DateTime format strings and special format specifiers. The value of "M" is ambiguous because it is a standard and specialized format specifier. The DateTime implementation will choose a standard formatter to format the client in case of conflict, therefore, it wins here.

The easiest way to eliminate the ambiguity is to prefix M with% char. This char way of saying the following should be interpreted as a custom formatter

 DateTime.Now.ToString("%M"); 
+8
source

Why not use DateTime.Now.Month ?

+5
source

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

+4
source

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

 DateTime.Now.ToString("''M") 
+2
source

It is worth noting that the% prefix is ​​required for any string with a single character when using the DateTime.ToString(string) method, even if this string is not one of the built-in format string format templates; I ran into this problem while trying to get the current hour. For example, a code snippet:

 DateTime.Now.ToString("h") 

will throw a FormatException . Change above:

 DateTime.Now.ToString("%h") 

indicates the current hour.

I can only assume that the method looks at the length of the format string and decides whether it represents an embedded or custom format string.

0
source

All Articles