Dio
Dio

Reputation: 660

How to create a DateTime object not in the current culture

I'm really drawing a blank on this one. I've been working on globalization but the DateTime seems to always revert back to the CurrentThread's culture. I broke this down into smaller steps hoping to find my issue, but it's starting to drive me crazy.

I've got a textbox with the date expressed as a string:

        // the CurrentThread's culture is de-DE
        // My test browser is also set to de-DE
        IFormatProvider culture = new System.Globalization.CultureInfo("de-DE", 
               true);

        // en-US culture, what I'd ultimately like to see the DateTime in
        IFormatProvider us_culture = new System.Globalization.CultureInfo("en-US", 
               true);

        // correctly reads the textbox value (22.7.2010 into a datetime)
        DateTime dt= DateTime.Parse(txtStartDate.Text, culture, 
                System.Globalization.DateTimeStyles.NoCurrentDateDefault);

        // correctly produces a string 7/22/2010
        string dt2 = dt.ToString(us_culture);

At this point I want a DateTime that's in en-US I've tried both:

        DateTime dt3 = Convert.ToDateTime(dt2, us_culture); 
        DateTime dt3 = DateTime.Parse(dt2, us_culture);

But both produce de-DE DateTimes. My motivation in asking this question is the rest of the business logic is going to be calling dt2.toString() and will result in an incorrect date time string. I realize I could change toString() to be toString(us_culture) but I'd rather not change all of the rest of the business logic to accomodate this change.

Is there a way to get a DateTime in a culture other than the CurrentThread's culture?

Thank you for your time, I've been banging my head against this for too long.

Upvotes: 4

Views: 4787

Answers (3)

Jesper Palm
Jesper Palm

Reputation: 7248

The parameter less overload of ToString() will always output the date according to the CurrentCulture setting. This is what you want 99 times of 100.

If you don't want to use the overload you could manually set the CurrentThread.CurrentCulture to what you want.

System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE");

But understand that this will change for everything in your application.

Upvotes: 2

Charles Cavalcante
Charles Cavalcante

Reputation: 1618

try using custom data format:

string dt2 = dt.ToString("m/d/yyyy");

Upvotes: 1

Will A
Will A

Reputation: 25008

A DateTime object is just that - a date/time, it's culture agnostic. You'll need to format the dates using a specific culture if that's what you're after.

Upvotes: 4

Related Questions