简体   繁体   中英

Getting system.formatexception

im getting an error that String was not recognized as a valid Date Time.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.FormateException: String was not recognized as a valid Date Time.

Here is the place where I get the exception:

string validFrom="dd/MM/yyyy";
    {
        lstExchangeRates.Add(new KangoGiftRepository.Orm.ExchangeRate(1, cell.Value.ToString(), decimal.Parse(importSheet.Cells[startRow, 2].Value.ToString()), DateTime.ParseExact(validFrom, "dd/MM/yyyy", null)));
        startRow++; cell = importSheet.Cells[startRow, 1];
        valid = cell?.Value != null && cell.Value.ToString().Length == 3;
    }

You are getting the error because your string is not in a valid date format.

In your code sample, validFrom should be the actual value, not the date format string. You're getting the error because 'dd/MM/YYYY' cannot be parsed into 'dd/MM/yyyy'. '23/10/2016' can be parsed into 'dd/MM/yyyy'.

Here is a code snippet to parse dates:

  string[] dateValues = { "30-12-2011", "12-30-2011", 
                          "30-12-11", "12-30-11" };
  string pattern = "MM-dd-yy";
  DateTime parsedDate;

  foreach (var dateValue in dateValues) {
     if (DateTime.TryParseExact(dateValue, pattern, null, 
                               DateTimeStyles.None, out parsedDate))
        Console.WriteLine("Converted '{0}' to {1:d}.", 
                          dateValue, parsedDate);
     else
        Console.WriteLine("Unable to convert '{0}' to a date and time.", 
                          dateValue);
  }

To learn more about parsing dates, visit https://msdn.microsoft.com/en-us/library/w2sa9yss(v=vs.110).aspx

To learn about valid format strings visit https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx

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