views:

718

answers:

1

Hi, How to convert the string "28/09/2009" to DateTime in an specific format? Ex: I want to convert "2009-09-28 17:30:40" to DateTime. I want to convert "28/09/2009 17:30:40" to DateTime. I want to convert "20090928 17:30:40" to DateTime.

There is multiples possible formats. I try this:

string[] formats = new string[] {"yyyymmdd","yyyymmddThhmmss","yyyy/mm/dd  hh:mm:ss","yyyy/mm/dd","yyyy-mm-dd hh:mm:ss","yyyy-mm-dd"};
        IFormatProvider culture = new CultureInfo("en-US", true);
        DateTime formattedDate = DateTime.ParseExact(aDate, formats, culture, DateTimeStyles.None);

These example throws an exception with the message "String was not recognized as a valid DateTime".

What's wrong in the code above?

+7  A: 

None of your formats put the day first, like this: "dd/MM/yyyy".

Also note the capital 'M', since lower case 'm' is for 'minutes'. You have a similar problem with your hours; since your samples all use 24 hour time you need a capital 'H'.

Your format string array should look like this:

string[] formats = {"dd/MM/yyyy", "yyyy-MM-dd HH:mm:ss", "dd/MM/yyyy HH:mm:ss", "yyyyMMdd HH:mm:ss"};

Those formats exactly match your supplied sample strings.

Additionally, you probably want to use the invariant culture rather than en-US in this case. Otherwise, the '/' character in your format strings is really a culture-specific date separator, which a user might over-ride on their local system.

Finally, since you're obviously having trouble matching up the strings up, you might want to use TryParseExact(), which works just like parse exact but uses an out parameter rather than returning the value, so that it can return a boolean to indicate success or failure rather than throwing an exception.

See the complete format string reference here:
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

Joel Coehoorn