Search code examples
c#asp.netdatetimedatetryparse

DateTime.TryParse issue with dates of yyyy-dd-MM format


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.


Solution

  • This should work based on your example "2011-29-01 12:00 am"

    DateTime dt;
    DateTime.TryParseExact(dateTime, 
                           "yyyy-dd-MM hh:mm tt", 
                           CultureInfo.InvariantCulture, 
                           DateTimeStyles.None, 
                           out dt);