I have the following date in string format "2011-29-01 12:00 am" . Now I am trying to convert that to datetime format with the following code:
DateTime.TryParse(dateTime, out dt);
But I am alwayws getting dt as {1/1/0001 12:00:00 AM} , Can you please tell me why ? and how can I convert that string to date.
EDIT: I just saw everybody mentioned to use format argument. I will mention now that I can't use the format parameter as I have some setting to select the custom dateformat what user wants, and based on that user is able to get the date in textbox in that format automatically via jQuery datepicker.
You need to use the
ParseExact
method. This takes a string as its second argument that specifies the format the datetime is in, for example:If the user can specify a format in the UI, then you need to translate that to a string you can pass into this method. You can do that by either allowing the user to enter the format string directly - though this means that the conversion is more likely to fail as they will enter an invalid format string - or having a combo box that presents them with the possible choices and you set up the format strings for these choices.
If it's likely that the input will be incorrect (user input for example) it would be better to use
TryParseExact
rather than use exceptions to handle the error case:A better alternative might be to not present the user with a choice of date formats, but use the overload that takes an array of formats:
If you read the possible formats out of a configuration file or database then you can add to these as you encounter all the different ways people want to enter dates.
Try using safe TryParseExact method
That works:
If you give the user the opportunity to change the date/time format, then you'll have to create a corresponding format string to use for parsing. If you know the possible date formats (i.e. the user has to select from a list), then this is much easier because you can create those format strings at compile time.
If you let the user do free-format design of the date/time format, then you'll have to create the corresponding
DateTime
format strings at runtime.This should work based on your example "2011-29-01 12:00 am"