I have a project given to me to fix some issues there.
There is an Excel sheet that has a date column. Now I am checking if the date is valid with the below code. After the try
, I keep getting an error
String '43941' was not recognized as a valid DateTime
I have tried some code on StackOverflow but none fix this problem for me.
public ValidationResult IsDateValid(ExcelWorksheet workSheet, int noOfRow)
{
ValidationResult validationResult = new ValidationResult();
validationResult.ErrorColIndex = 3;
validationResult.IsValid = true;
// be on the first column [r,c]
int row = 2;
for (int i = 2; i <= noOfRow; i++) //start from the second row
{
if (!string.IsNullOrEmpty(workSheet.Cells[i, 3].Text))
{
string date = workSheet.Cells[i, 3].Value.ToString();
// will throw exception if the fields in tenor are invalid
try
{
DateTime p = DateTime.ParseExact(date.Trim(), "M/dd/yyyy", null);
}
catch (Exception ex)
{
validationResult.Message = "Invalid Date.";
validationResult.IsValid = false;
validationResult.ErrorRowIndex = row;
break;
}
}
else
{
validationResult.Message = "Empty Date.";
validationResult.IsValid = false;
validationResult.ErrorRowIndex = row;
break;
}
++row;
}
return validationResult;
}
I will be glad if someone can point out what I am doing wrong
Thanks