Kyle
Kyle

Reputation: 4366

Strange DateTime.ToString behavior

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

Upvotes: 1

Views: 230

Answers (5)

Marcello Faga
Marcello Faga

Reputation: 1204

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"

Upvotes: 3

Kyle
Kyle

Reputation: 4366

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

Upvotes: 2

Kyle Rosendo
Kyle Rosendo

Reputation: 25277

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

Upvotes: 1

Nenad Dobrilovic
Nenad Dobrilovic

Reputation: 1555

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.

Upvotes: 0

Tony Abrams
Tony Abrams

Reputation: 4673

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

Upvotes: 0

Related Questions