Walter Fabio Simoni
Walter Fabio Simoni

Reputation: 5729

Convert DateTime to US is not good

I have a DateTimePicker in WPF. The dateTimePicker give me an European Format

In my DateTimePicker, i select "01/02/2014" ( in european format )

I would like to read the value, and convert it in a shortDateString with the US culture.

I have done this :

CultureInfo m_UsCulture = new CultureInfo("en-us");
string str = m_dDate.Date.ToShortDateString().ToString(m_UsCulture);

The str variable is : "01/02/2014" instead of "2/1/2014"

The ShortDateString appear to be OK, but not the "ToString(m_UsCulture);".

I would like to do this in a one line please. Have you an idea for this error ?

Thanks a lot :)

Upvotes: 0

Views: 1242

Answers (2)

ken2k
ken2k

Reputation: 48975

ToShortDateString uses the current culture, so you can't specify your US culture with this method (unless you change the current culture). I would use ToString instead, and the US-specific short date pattern:

CultureInfo usCulture = CultureInfo.GetCultureInfo("en-us");
var stringRep = yourDate.ToString(
    usCulture.DateTimeFormat.ShortDatePattern, 
    usCulture);

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1500305

The dateTimePicker give me an European Format

That could only be true if you're using the Text property. I suggest you use the SelectedDate property, which will give you a DateTime? instead - and a DateTime doesn't have a format... it's up to you to format it however you want.

Then to convert them to US short date format, you should use ToString and specify d (for short date format) and the culture at the same time:

string str = m_dDate.Date.ToString("d", m_UsCulture);

Your current code is using DateTime.ToShortDateString() which will use the current culture, and then calling ToString on the resulting string which won't care about the culture you pass it.

Upvotes: 4

Related Questions