views:

80

answers:

5

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")

A: 

I think you have the format strings wrong. Try "dd" and "MM".

Tony Abrams
+1  A: 

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
Kyle Rozendo
+3  A: 

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"
Marcello Faga
What about this page: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
Kyle
Sorry for the late answer. I checked in your page and i noticed my previous answer was not complete. The page you provided said the true. You can test the new code to proove it by yourself (i hope it works)
Marcello Faga
Thanks for your update. Yes, the d with the space after it works as does the "%d" which I've indicated below.
Kyle
A: 

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.

Nenad
So how is this resolved?
Kyle
+2  A: 

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

Kyle