0

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?

Community
  • 1
  • 1
C_sharp
  • 408
  • 5
  • 26

3 Answers3

4

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

Habib
  • 219,104
  • 29
  • 407
  • 436
1

Your MM (month) would be equal to 15. There are only 12 months in the year not 15.

osahon
  • 51
  • 2
0

Try like this.

      string DatePaid="9/15/2012";

 var date = DateTime.ParseExact(DatePaid, "M/dd/yyyy", CultureInfo.InvariantCulture);