Search code examples
c#asp.netdatetimeglobalizationculture

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.


Solution

  • 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.