簡體   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