How to convert the string "28/09/2009"
to DateTime
in a 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 are multiple possible formats. I tried 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);
This example throws an exception with the message "String was not recognized as a valid DateTime".
What's wrong in the code above?
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:
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 anout
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/8kb3ffffd4.aspx