Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 824
Mike Gates Avatar asked Nov 28 '22 15:11

Mike Gates


2 Answers

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.

like image 82
Franci Penov Avatar answered Nov 30 '22 23:11

Franci Penov


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");
like image 42
JaredPar Avatar answered Nov 30 '22 22:11

JaredPar