I want to parse strings with date that can have different formats like:

"21.12.12", "4,12,2011", "30 Jun 11", "16 12 2013" , "April 2013", "12. April 2012", "12, März 2011".

I have this code:

string[] ll = {"en-US", "de-DE"}; 
date = "4,12,2011";
foreach (string l in ll) {
   if (DateTime.TryParse(date, new CultureInfo(l),
                            DateTimeStyles.None, out pDate)) {
       return pDate;//.ToString("dd.MM.yyyy");
   }
}

And I have problems with dates like this:

"21.12.12" is parsed like "21 December 2012", and it is OK

"4,12,2011" is parsed like "12 April 2011", it is not OK, I need "4 December 2011"

How to set order for Day and Month?

It must be Day before Month.

有帮助吗?

解决方案 5

This is specific for the en-US culture. It may be strange for us Europeans, but Americans really write month before day in dates. You may use en-GB instead - it will handle the same names of months and the European order.

其他提示

To specify the format(s) of the string you are passing, you should use the ParseExact method.

Use DateTime.ParseExact, it has also an overload tha allows to pass a string[[] for all allowed formats.

string[] dates = new[] { "21.12.12", "4,12,2011", "30 Jun 11", "16 12 2013", "April 2013", "12. April 2012", "12, März 2011" };
CultureInfo germanCulture = CultureInfo.CreateSpecificCulture("de-DE"); // you are using german culture
string[] formats = new[] { "dd/MM/yy", "d,MM,yyyy", "dd MMM yy", "dd MM yyyy", "MMMM yyyy", "dd. MMMM yyyy", "dd, MMMM yyyy"};

foreach (string dateString in dates)
{
    DateTime dt = DateTime.ParseExact(dateString, formats, germanCulture, DateTimeStyles.None);
    Console.WriteLine(dt.ToString());
}

I have used german culture because your date-strings contain german month names. So this code works even if the current culture is different.

All of the test dates that you gave actually parse correctly in the de-DE culture that you specify. The problem comes that you try to parse it in the american culture first where they use mm.dd.yyyy style formats.

The correct solution in general is to always make sure you know what culture you are using when parsing the string rather than guessing. If you have to guess you will get these kinds of problems at times.

In this case though it looks like they are all acceptable de-DE date strings so you can just parse them as that without needing the loop of trying different cultures (which as mentioned is probably never likely to be a perfect result).

According to your code

  string[] ll = {"en-US", "de-DE"}; 

you initially try parse DateTime with "en-US" culture; so the "4,12,2011" will be parsed as americans do - MM/DD/YYYY - month the first (12 April). Change order in your array

  string[] ll = {"de-DE", "en-US"}; 

and "4,12,2011" will be 4 December

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top