Search code examples
c#stringdatetime-formatstring-conversion

Convert a string Date to the DateTime Format?


I have very well researched all the question like this, this and this. However, no matter what I try I still get the Format exception:

string DatePaid="9/5/2012";
var date = DateTime.ParseExact(DatePaid, "dd/MM/yyyy", CultureInfo.InvariantCulture);

I have no idea what am I doing wrong?


Solution

  • EDIT:

    Since you changed the date string your question to "9/5/2012" now it could be Day/Month/Year or Month/Day/Year, Assuming that it is Day/Month/Year, You are getting the exception because of using dd since that requires day part to be in double digits. So in your string the day 9 should be 09.

    You can use single d and M which would work for both single and double digit day and month part respectively.

    So your code should be:

    string DatePaid = "9/5/2012";
    var date = DateTime.ParseExact(DatePaid, "d/M/yyyy", CultureInfo.InvariantCulture);
    

    Old Answer


    You are getting the format exception because your format is wrong. Your format should be "M/dd/yyyy" or if you have single digit day part then use d which would parse both single and double digit day part.

    string DatePaid = "9/15/2012";
    var date = DateTime.ParseExact(DatePaid, "M/d/yyyy", CultureInfo.InvariantCulture);
    

    See: Custom Date and Time Format Strings