繁体   English   中英

在 asp.net 核心 3 中,字符串未被识别为有效的 DateTime

[英]String was not recognized as a valid DateTime in asp.net core 3

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;
        }

好的,这是您的代码行:

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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM