0

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

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

我之前可以在stackoverflow(检查代码)上解决此问题,但今天再次测试上传时,问题仍然存在。我已经检查了 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;
        }

4

2 回答 2

0

好的,这是您的代码行:

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

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

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

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

于 2020-06-03T14:20:14.780 回答
0

尝试在日期格式中添加秒数:

代替

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);
于 2020-06-03T14:23:12.490 回答