I have a bunch of date strings in the cells that I am pulling, for example:
No no. You have a combination of strings that look like dates and that look like strings . This is an Excel issue, not a C # issue.
Not sure if you are creating a spreadsheet or getting it from somewhere else. But the problem is that Excel is trying to parse the text as it is being entered into the cell. In this case, he makes the wrong decisions about the dates that he finds.
If you enter a date like "03/05/2011", Excel (incorrectly) will analyze it as March 5, 2011 and save it as a numeric date code (40607). Then it applies the date formatting to the cell (it uses m / d / yyyy on my machine).
If you enter a date like 05/31/2011, Excel will not be able to parse it as a date and save it as text.
To prove this, select the cells and go to Edit> Clear> Formats. All the "bad dates" will simply be displayed as numbers, everything else will look like dates.
You have several options:
- Correct the data before entering it into Excel (add everything with "so that everything is entered as text", or do not forget to create a spreadsheet on the machine with the correct date settings.)
- Do not use
.Value.ToString() from Excel, just use .Text . This will ignore the bad parsing that Excel did, and should give you a consistent text value (of both types) that you can ParseExact with C # for other answers.
(2) much simpler, and if spreadsheets already exist, may be your only choice.
Bradc source share