字符串在核心 3 中未被识别为有效的日期时间 asp.net



excel 上传中的日期格式返回此错误。

{"String '6/3/2020 12:00:00 AM' was not recognized as a valid DateTime."}

我之前能够在堆栈溢出(检查代码(上解决问题,但是今天再次测试上传时,问题仍然存在。我已经检查了StackOverflow上几乎所有可用的建议,但似乎没有一个有效。

在 excel 工作表上,我有6/3/2020但在代码中我得到了6/3/2020 12:00:00 AM

我整天都在试图解决这个问题

for (int i = 2; i <= noOfRow; i++)   //start from the second row
{
if (!string.IsNullOrEmpty(workSheet.Cells[i, 3].Text))
{
var date = workSheet.Cells[i, 3].Value.ToString();
//will throw exception if the fields in tenor are invalid
try
{
DateTime d = DateTime.ParseExact(date, "M/d/yyyy HH:mm tt", CultureInfo.InvariantCulture);
}
catch (Exception ex)
{
validationResult.Message = "Invalid Date.";
validationResult.IsValid = false;
validationResult.ErrorRowIndex = row;
logger.Error(validationResult.Message);
break;
}
}
else
{
validationResult.Message = "Empty Date.";
validationResult.IsValid = false;
validationResult.ErrorRowIndex = row;
logger.Error(validationResult.Message);
break;
}
++row;
}
return validationResult;
}

好的,这是你的代码行:

DateTime d = DateTime.ParseExact(date, "M/d/yyyy HH:mm tt", CultureInfo.InvariantCulture);

这是您尝试转换的日期字符串:

"6/3/2020 12:00:00 AM"

请注意日期字符串如何包含小时、分钟和秒,但格式字符串只有小时和分钟。DateTime.ParseExact需要您提供传入字符串的确切格式。

尝试添加秒数以设置日期格式:

取代

DateTime d = DateTime.ParseExact(date, "M/d/yyyy hh:mm tt", CultureInfo.InvariantCulture);

DateTime d = DateTime.ParseExact(date, "M/d/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);

最新更新