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?
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.
You can use the methods like Convert. ToDateTime(String), DateTime. Parse() and DateTime. ParseExact() methods for converting a string-based date to a System.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With