Strange DateTime.ToString behavior
-
30-09-2019 - |
Question
I have the following line of code inside of a function:
String value = endDate.Value.ToString(dateFormatStr);
//endDate is a DateTime? object (returned from a LINQ to SQL query).
In the particular instance I am experiencing odd behavior, the value of endDate is {10/2/2010 12:00:00 AM}. Here's my results:
dateFormatStr="d" => value="10/2/2010" (I would expect "2")
dateFormatStr="M" => value="October 2" (I would expect "10")
Solution 2
Need to put a "%" in front of the format when using a single character custom format that matches a standard format. For example:
endDate.Value.ToString("%d");
See http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx#UsingSingleSpecifiers
OTHER TIPS
Your result agreed with the microsoft specification
Use the relative DateTime properties in order to get Day, Month and Year
****Edited****
Check this code to see how the 'd' character changes its behaviour depending on it is alone or it is part of a pattern string
DateTime time = DateTime.Now;
// 'd' is part of a pattern expression: "d "
MessageBox.Show(time.ToString("d "));
// result: "24 "
// 'd' defines a specific pattern: "short date"
MessageBox.Show(time.ToString("d"));
//result : "24/08/2010"
Have a look at this site.
This is not irregular at all, in fact you are using the single-character standard formats (here) for dates.
If you are wanting to split your formats in the way you are expecting them, either use dd
and MM
, or (if this is what you need to do) rather just take the integer value from the DateTime
object.
I.e:
endDate.Value.Day
endDate.Value.Month
I think you have the format strings wrong. Try "dd" and "MM".
Some patterns has some kind of short name - single character name, which is the same as used in full patterns, but unfortunately has different meaning. You just have discovered that.
This is another site which can be useful.