tags:

views:

905

answers:

4

Hey guys,

I experiencing a strange behavior of C#. Its some thing like this..

var date = DateTime.Now.ToString("MM/dd/yyyy");

I expecting out to be

04/24/2009

but in actuall its returning

04-24-2009

and my OS culture is en-GB, I'm using .Net 3.5 and WPF

any solutions please... ???

+1  A: 

check out my question's answer.

Vikas
Summary: the '/' character is a special token that means 'culture-specific separator'. Manually specify the invariant culture to make .Net ignore that.
Joel Coehoorn
Actually, 'ignore' in my previous comment was wrong. Translate back to '/' would be more accurate
Joel Coehoorn
+3  A: 

It uses the separator set up in the regional settings, since "/" is the substitute character for the separator.

You can create your own DateTimeFormat instance with different separators.

Lucero
+14  A: 

According to the MSDN docs for custom date and time format strings, / is a placeholder:

Represents the date separator defined in the current DateTimeFormatInfo.DateSeparator property. This separator is used to differentiate years, months, and days.

If you want a definite slash, use "MM'/'dd'/'yyyy":

DateTime.Now.ToString("MM'/'dd'/'yyyy")
Jon Skeet
+1  A: 

Try calling ToString on the date itself and passing the CultureInfo.InvariantCulture object:

string date = yourDate.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture));
Justin Niessner