Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 628
Luiz Costa Avatar asked Sep 28 '09 21:09

Luiz Costa


People also ask

How do I convert a DateTime to a specific format?

The ToString() method of the DateTime class is used to convert a DateTime date object to string format. The method takes a date format string that specifies the required string representation.

How do I convert a string to a date in C #?

You can use the methods like Convert. ToDateTime(String), DateTime. Parse() and DateTime. ParseExact() methods for converting a string-based date to a System.

Can we convert string to date?

Convert the String to Date using LocalDate. parse() method. If converted successfully, then print the Date. If the String pattern is invalid, then IllegalArgumentException is thrown.


1 Answers

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

like image 144
Joel Coehoorn Avatar answered Oct 03 '22 03:10

Joel Coehoorn