How to convert a string to a specific DateTime format in C #?

How to convert a string "28/09/2009"to DateTimein a specific format? Example: I want to convert "2009-09-28 17:30:40" to DateTime. I want to convert "09/28/2009 17:30:40" to DateTime. I want to convert "20090928 17:30:40" to DateTime.

There are several 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 is wrong in the code above?

+5
source share
1 answer

None of your format does not put the first day, for example "dd/MM/yyyy".

"M", "m" "". ; 24 , "H".

:

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

.

, , , , en-US. '/' - , .

, , TryParseExact(), , , out , , , , .

. :
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

+12

All Articles