-1

I am trying to read date from excel using code

String ss = (String)w.Cells[2 + i, 4].Value2;
dRow[3] = DateTime.Parse(ss);

Code works when ss = "12/11/2015" but gives error

String was not recognized as a valid DateTime

when ss = "13/11/2015"

It gives error because month can not be 12 but it is taking date as month. This is what I think. Same code is working on other PC. Do I need to check my date time format or anything like date setting.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Hot Cool Stud
  • 1,145
  • 6
  • 25
  • 50

1 Answers1

5

DateTime.Parse uses standard date and time format of your CurrentCulture settings by default.

Looks like your CurrentCulture has MM/dd/yyyy format as a short date format and since there is no month as 13 in Gregorian Calendar (which probably uses as a Calendar for your CurrentCulture), you get FormatExcetion.

You can use DateTime.ParseExact method to specify your format exactly like;

dRow[3] = DateTime.ParseExact("13/11/2015", "dd/MM/yyyy", 
                              CultureInfo.InvariantCulture);

If you get this as an input and you want to parse it to DateTime, you have to know which format it has. Other than that, it can generate ambiguous scenarios.

For example; what 01/02/2015 should be parsed as? 1st February or 2nd January?

You shouldn't assume that every string you supplied perfectly parsed with DateTime.Parse method. It is not that smart.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364