简体   繁体   中英

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

The date format in an excel upload is returning this error.

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

I was able to fix the issue before here on stackoverflow(Check code) but today while testing the upload again, the problem persists. I have checked almost all the suggestions available on StackOverflow but none seem to be working.

On the excel sheet I have 6/3/2020 but in the code I got 6/3/2020 12:00:00 AM

I have been trying to fix this all day

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

OK, here's your line of code:

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

And here is the date string you are trying to convert:

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

Notice how the date string contains hours, minutes, and seconds, but your format string only has hours and minutes. DateTime.ParseExact needs you to supply the exact format of the incoming string.

Try add seconds to format of date:

Replace

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

with

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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