-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.

1
  • possible, because there is no 13th month in a year...? Commented Dec 18, 2015 at 13:30

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.