Vlado Pandžić
Vlado Pandžić

Reputation: 5048

Converting date string in unknown format to datetime c#

I don't know format of the DateTime because web page has more than one language and more than one Datetime format are available. I had to change poland dateformat in datepicker UI to d.m.yyyy although ISO standard is YYYY-mm-dd. .NET uses ISO standard but whenever I try to use Convert.ToDateTime(stringDate) I get exception String is not recognized as valid DateTime . I tried using Convert.ToDateTime(stringDate,CultureInfo.InvariantCulture) but it does not help. How to successfully convert to DateTime?

Example: item.arrival is string which can be in more than 10 formats. Convert.ToDateTime works for them all. BUT: item.arrival dateformat for poland language is not anymore yyyy-mm-dd (because I had requirement to change it) so Convert.ToDateTime not works anymore only for poland language. New format is 13.06.2015. Because of that, because format is not ISO standard for poland language .NET fails to do conversion. I hope it is more clear now. ArrivalDate = Convert.ToDateTime(item.arrival, CultureInfo.InvariantCulture),

Upvotes: 0

Views: 1060

Answers (2)

Vlado Pandžić
Vlado Pandžić

Reputation: 5048

This is what I did. I put it inside some PageBase class so it should more general and less error prone solution than some "if-poland-date" statements around the project.

CultureInfo newCulture = (CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture;
        if (newCulture.TwoLetterISOLanguageName == "pl")
        {

            DateTimeFormatInfo myDTFI = new CultureInfo("hr-HR", false).DateTimeFormat;
            newCulture.DateTimeFormat = myDTFI;
            CultureInfo ci = new CultureInfo("pl-PL");
            DateTimeFormatInfo dateformat = new DateTimeFormatInfo();
            ci.DateTimeFormat = myDTFI;
            CultureAndRegionInfoBuilder obj = new CultureAndRegionInfoBuilder("pl-PL", CultureAndRegionModifiers.Replacement);
            obj.LoadDataFromCultureInfo(ci);
            CultureAndRegionInfoBuilder.Unregister("pl-PL");
            obj.Register();

        }

Upvotes: 1

Les
Les

Reputation: 10605

I had to change poland dateformat in datepicker UI to d.m.yyyy ... Example: item.arrival is string which can be in more than 10 formats. Convert.ToDateTime works for them all. BUT: item.arrival dateformat for poland language is not anymore yyyy-mm-dd (because I had requirement to change it)

Based upon what you say, your date time conversion works for all but Polish, and you (in your code) know when it is Polish. So, handle Polish special using the format you have been required to use, and handle the other nine normally.

Upvotes: 1

Related Questions